java - Creating object with reference to Interface -
a reference variable can declared class type or interface type.if variable declared interface type, can reference object of class implements interface.
based on above statement have made code on understanding. said above declared interface type, can reference object of class implements interface.
but in code displaying displayname()method undefined @ objparent.displayname();.
public class overridenclass { public static void main(string[] args) { pritable objparent = new parent(); objparent.sysout(); objparent.displayname(); } } interface pritable { void sysout(); } class parent implements pritable { public void displayname() { system.out.println("this parent name"); } public void sysout() { system.out.println("i printable interfacein parent class"); } }
i sure have understood wrong way.
can 1 explains same.
thanks reply.
but in code displaying displayname()method undefined.
right, because displayname
not defined in pritable
interface. can access methods defined on interface through variable declared having interface, if concrete class has additional methods. that's why can phone call sysout
, not displayname
.
the reason more apparent if consider illustration this:
class bar { public static void foo(pritable p) { p.sysout(); p.displayname(); } } class test { public static final void main(string[] args) { bar.foo(new parent()); } }
the code in foo
must not rely on other featured in pritable
interface, have no thought @ compile-time concrete class may be.
the point of interfaces define characteristics available code using interface reference, without regard concrete class beingness used.
java
No comments:
Post a Comment