java - 动态方法调度和运行时多态性错误

标签 java methods polymorphism run-time-polymorphism

我正在尝试理解动态方法分派(dispatch)。

class A {
int i=10;
void callme() {
    System.out.println("Inside A's callme method");
} }
class B extends A {
int j=20;
    void callme() {
        System.out.println("Inside B's callme method");
} }
class C extends A {
int k=30;
void callme() {
    System.out.println("Inside C's callme method");
} }
class  Over_riding_loading{
    public static void main(String args[]) {
        A a = new A(); 
        B b = new B(); 
        C c = new C(); 
        A r; 
        B r; //error when i am using this instead of A r;
        C r; //error when i am using this instead of Ar and B r;
        r = a;

        r.callme();
        System.out.println(r.i);//prints 10
        r = b; 
        r.callme(); 
        System.out.println(r.j);//j cannot be resolved or is not a field--what does this mean?
        r = c; 
        r.callme();
        System.out.println(r.k);//k cannot be resolved or is not a field
} }

为什么会出现错误?为什么我不能创建 B 或 C 类型的变量 r 并调用 callme() 方法?

编辑:为了澄清一些事情,我并不想使用相同的变量名,我想说的是而不是 A r;我正在尝试使用 B r 并保持其余代码相同。

最佳答案

不同类型(在同一范围内)不能使用相同的变量名

将您的主要方法修改为

   public static void main(String args[]) {
    A a = new A();
    B b = new B();
    C c = new C();
    A r;
    //you cannot have same variable name for different types (in same scope)
    //B r; // error
    //C r; // error
    r = a;

    r.callme();
    System.out.println(r.i);// prints 10
    r = b;
    r.callme();

    //here you're getting error because object is available at runtime, what you are getting is a compile time error
    System.out.println(r.j);// can be resolved by casting it as System.out.println(((B)r).j)
    r = c;
    r.callme();
    // here you're getting error because object is available at runtime, what you are getting is a compile time error
    System.out.println(r.k);// can be resolved by casting it as System.out.println(((C)r).k);
}

希望对你有帮助!!

关于java - 动态方法调度和运行时多态性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61493950/

相关文章:

Java:重载 java.lang.Number 的(通用)方法

ruby - 为什么我在此 Ruby 代码中收到 NoMethodError?

php - 如何获取类名和方法名?

c++ - 指针指针方法 C++

c++ - 如何检查多态子类的模板参数类型

Java::在运行时获取参数化类型名称

java - 执行循环程序

java - 在使用反射实现向后兼容性方面需要帮助

java - REST lib 为 Java REST API 提供了什么

haskell - monads Writer m 和 Either e 是绝对对偶的吗?