gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:39:11 25 4
gpt4 key购买 nike

我正在尝试理解动态方法分派(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com