简体   繁体   English

为什么Java中的多态性从超类调用方法

[英]why polymorphism in java call the methods from the superclass

///Example code here
Superclass{ 
    method1(){ 
      print(do1);
     }
    method2(){}
  }
Subclass extends Superclass{
   ///override method1
 method1(){ 
      print(do2);
    }
 method3(){}
 }

I have a question for the polymorphism in java, which is when Superclass s =new Subclass() . 我对Java中的多态性有一个疑问,那就是何时Superclass s =new Subclass() the "s" object always invoke the method in the Superclass, but when the override method happened, the "s" will point back to the override methods. “ s”对象总是调用超类中的方法,但是当覆盖方法发生时,“ s”将指向覆盖方法。

Update: So, the question is who will create a heap address for the reference "s", if it can be compiled and running in the end. 更新:因此,问题是谁可以为引用“ s”创建堆地址,如果它可以最终编译并运行。 If the Superclass created it, why new Subclass() rather than new Superclass(). 如果超类创建了它,为什么要使用新的Subclass()而不是新的Superclass()。 If the Subclass created it, why cannot use s.method3(). 如果子类创建了它,为什么不能使用s.method3()。

s can call method3. 可以调用method3。 You just have to cast it first. 您只需要先投射它即可。 If they allowed s to call method3 as Superclass, it wouldn't make sense because not ALL Superclass can call method3. 如果他们允许s调用method3作为超类,那是没有意义的,因为并非所有超类都可以调用method3。

Dynamic binding of method will decide at run times , so first when you call method with s as its reference of super class compiler will always first check if superclass has that method or not. 方法的动态绑定将在运行时确定,因此,当您使用s作为超类编译器的引用调用方法时,将始终首先检查超类是否具有该方法。 there are 2 case 有2种情况

1. If super class has the method JVM will go ahead and check in child class, If child class has overriding method then that method will be called , if child class doesn't have that method than normally parent class method will call. 1.如果超类具有方法,则JVM将继续检查子类;如果子类具有重写方法,则将调用该方法;如果子类没有该方法,则通常将调用父类方法。

2. If super class does not have that method , then compilation fails as compiler could not identified any method in class of reference variable 2.如果超类没有该方法,则编译将失败,因为编译器无法在引用变量的类中标识任何方法

So in your case if super class doesn't have method3 then it will defiantly gives compilation error 因此,在您的情况下,如果超类没有method3,那么它将反抗地给出编译错误

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

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