我正在做这个学校练习,我不知道为什么以下两种情况会有不同的结果。有人可以解释为什么在第一种情况int x
下A是100吗?int x
C中的阴影不是int x
在A中吗?我也在代码中评论了我的问题。非常感谢!
class A { // Case 1
public int x = 1;
public String k() { return "A" + this.x; }
}
class B extends A {
public int x = 10;
}
class C extends B {
public int x = 100;
public String k() { return "C" + this.x; }
}
class TestABC {
public static void main(String[] args) {
A a1 = new C();
C c1 = new C();
}
}
System.out.println(a1.x +"," + c1.x);// It prints out 1, 100.
//However I thought it'd print out 100, 100, as the int x in C shadows int x in A.
另一个案例是
class A1 { //case 2
int x=10;
public void method() {
System.out.print("A:" + this.x + " ");
}
}
class B1 extends A1 {
int x=20;
public void method() {
System.out.print("B:" + this.x + " ");
}
public static void main(String args[]) {
A1 s = new B1();
s.method();// It prints out B: 20.
//What's the difference between this one and a1.x in the previous example?
//Why it prints out the subclass but in the previous code a1.x prints out the parent class?
}
}
第一种情况会打印出来,1, 100
因为它获得了VARIABLE的值,例如:
Get the value of x in A and get the value of x in C
覆盖仅发生在不带有变量的方法上。这就是为什么在第二种情况下,它会在B1
而不是中调用方法A1
这称为运行时多态。
编辑2:
让我进一步解释一下:
当我们在运行时调用方法时,JVM不会查看引用变量的类型,而是会查看对象的类型并运行该方法。
但是对于变量,这是另一种方式,JVM不会查看对象的类型,而是会查看引用变量的类型,并获取该变量。
给出以下示例:
class Animal {
String whatAmI = "An Animal";
public void sayHi() {
System.out.println("Hi from Animal");
}
}
class Dog extends Animal {
String whatAmI = "A Dog";
public void sayHi() {
System.out.println("Hi from Dog");
}
}
样品运行:
//Reference variable type //Object type
Animal anAnimal = new Animal();
Dog aDog = new Dog();
Animal anotherDog = new Dog();
anAnimal.sayHi(); //Hi from Animal
aDog.sayHi(); //Hi from Dog
anotherDog.sayHi(); //Hi from Dog
我们得到这些输出是因为JVMsayHi()
在对象的类型而不是引用变量的类型上调用了该方法。
但事实是,它与变量的工作方式不同。如果我们尝试以下操作:
System.out.println(anAnimal.whatAmI); //An Animal
System.out.println(aDog.whatAmI); //A Dog
System.out.println(anotherDog.whatAmI); //An Animal
我们有这些输出,因为JVMwhatAmI
从Reference变量的类型中获取变量。
记住这一点的一种技术是集中在等号(=)上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句