简体   繁体   English

具有接口的Java多态性

[英]Java Polymorphism With Interface

I am taking AP Comp Sci and we are learning about polymorphism and inheritance. 我正在参加AP Comp Sci,我们正在学习多态性和继承。 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( ); 如果类C1和C2都实现了接口Cint,则该接口具有方法“ whichIsIt”,并且如果C1 c = new C1(),则返回Cint。 is performed at one point of the program, then a later instruction c.whichIsIt( ); 在程序的某一点执行,然后执行后续指令c.whichIsIt(); will invoke the whichIsIt method defined in C1. 将调用C1中定义的whichIsIt方法。

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. Java对最终和重载方法具有早期绑定,而对重写方法具有后期绑定。 So unless whichIsIt method is final or overloaded the answer should be true. 因此,除非whichIsIt方法是最终方法或重载方法,否则答案应为true。 Also before java8 interfaces were not allowed to have method implementations. 同样,在java8接口之前,不允许使用方法实现。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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