java - java中的动态方法调度

标签 java inheritance casting

class A{
int a=10;   
public void show(){ 
    System.out.println("Show A: "+a);
    }
}

class B extends A{
public int b=20;    
public void show(){
    System.out.println("Show B: "+b);
    }
}



public class DynamicMethodDispatch {

    public static void main(String[] args) {

    A aObj = new A();       
    aObj.show();    //output - 10

    B bObj = new B();
    bObj.show();   //output - 20

    aObj = bObj;   //assigning the B obj to A..         
    aObj.show();  //output - 20 

    aObj = new B();
    aObj.show();  //output - 20
             System.out.println(bObj.b);  //output - 20 
    //System.out.println(aObj.b); //It is giving error



     }
}

在上面的程序中,我尝试调用 aObj.b 时遇到错误。
1.为什么我无法通过 aObj 访问该变量,尽管它指的是 B 类?
2. 为什么我可以访问 show() 方法?

最佳答案

您必须区分aObj静态类型aObj运行时类型

代码如

A aObj = new B(); 

产生一个 aObj 静态类型 A 和运行时类型 B 的变量。

编译器在决定允许或不允许什么时只会费心查看静态类型

您的问题:

1.why i'm not able to acess that variable through the aObj though it is refering to class B??

因为(通常)编译器无法知道 aObj 将在运行时引用 B 对象,仅它将引用某种形式的 A 对象。由于 .b 并非在所有 A 对象上都可用,因此编译器会认为“安全总比抱歉好” 并禁止它。

2.why i'm able to acess the method show()?

因为这个方法在所有A对象中都可用(如果没有在子类中声明,它仍然继承自A)。

关于java - java中的动态方法调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10595527/

相关文章:

java - 在 JScrollPane 中放置 JTextField 搜索栏

java - guava 和 apache 等效库之间有哪些重大改进?

Java:为什么我的列表包含不同的类型? (过滤列表)

types - 如何在erlang中使用-spec功能

java - 从 Heroku 中的 python 应用程序运行 java 子进程

java - 如何将多个 View 合并到一张位图中

java - Java中的方法重写-将子类对象分配给父类变量

c++ - 公共(public)继承类无法访问基类的重载非虚拟公共(public)方法?

javascript - Dijit 小部件构造函数抛出 "calling chained constructor"错误

C Actor : Is this expression coded correctly?