简体   繁体   中英

Java Polymorphism With Interface

I am taking AP Comp Sci and we are learning about polymorphism and inheritance. Our instructor gave us the following problem:

If classes C1 and C2 both implement an interface Cint, which has a method “whichIsIt”, and if C1 c = new C1( ); is performed at one point of the program, then a later instruction c.whichIsIt( ); will invoke the whichIsIt method defined in C1.

Supposedly the answer is false . However, this makes no sense to me. The whole point of polymorphism is that it uses dynamic binding and will use the method that is defined in the lowest class in the hierarchy. How can the answer to this question be false?

Java has early binding for final and overloaded method and late binding for overriden methods. So unless whichIsIt method is final or overloaded the answer should be true. Also before java8 interfaces were not allowed to have method implementations.

Cint c = new C1();
c.whichIsIt() //Assuming C1 overrides whichIsIt method defined in Cint, 
              //then this will call C1.whichIsIt method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM