java - How the compiler will get to know which print method should be called by obj.print();? -
here example of interface showing multiple inheritance.and want know how can achieve multiple inheritance interface , why can't use class?
interface printable // interface1 { void print(); } interface showable //interface2 { void print(); } class testtnterface1 implements printable,showable { public void print() { system.out.println("hello"); } public static void main(string args[]) { testtnterface1 obj = new testtnterface1(); obj.print(); //which print method called now? } }
first question:
the implementation satisfies both contracts, whether cast concrete class printable
or showable
, used same. notice there "impossible" situation, this:
public interface printable{ string print(); } public interface showable{ void print(); } public class impl implements printable,showable{ /*impossible implement because cannot have same method signature 2 different return types*/ }
the multiple inheritance imply there useful added each parent. example, if printable
have method #print
, showable
have method #show
, inheriting them both add functionality program.
if want combine functionality several concrete classes, might want composition instead of inheritance.
the answer second question more tricky. can find longer discussion here. while have been possible creators of java put in such option, have opened door pretty messed code. think of example gave: if printable
, showable
had concrete implementations #print
method? implementation should inheriting class have chosen?
Comments
Post a Comment