我有以下代码:
1. public class Tester
2. {
3. public static void main(String[] args)
4. {
5. A a = new B();
6. System.out.println(a.getClass()); //Prints class B
7. System.out.println(a instanceof A); //Prints true
8. System.out.println(a instanceof B); //Prints true
9. System.out.println(a.valA); //Prints 1
10. System.out.println(a.valB); //Compilation error
11.
12. }
13. }
14.
15. class A
16. {
17. int valA=1;
18. }
19.
20. class B extends A
21. {
22. int valB=2;
23. }
在第6行,它显示a是类型B的类型.但是当它到达第10行时,编译器会产生错误:location:类型A的变量a.
所以我的问题是:现在的类型究竟是什么?为什么getClass()显示它是类型B,但编译器在编译期间将其作为类型A抱怨?
此外,由于B的实例是真的,为什么我不能访问valB?
为了使事情更清楚:
编辑:我运行了这个语句:System.out.println(a);输出是B @ 36d98810,它以某种方式证明了B类的toString()方法已被执行.由于变量a可以访问类B中的toString()方法,为什么它不能访问也存在于类B中的valB?
解决方法:
来自加州大学伯克利分校的Jonathan Shewchuk教授解释了关于here的阴影.从18分钟开始. (如果链接更改只是谷歌搜索CS 61B第15讲:更多Java)
简而言之,对于变量,静态类型和动态类型,有两种类型.
Static type is its Type at compile time
Dynamic type is its Type at run time.
在你的例子中
A a = new B();
a的静态类型是A,a的动态类型是B.
In Java a variable gets its non static methods from dynamic type
(if the method exists in both the parent and child class)
and
its fields and static methods from the static type.
只有在子类中重写该方法时,才能在C#中实现
更新:
这条线
a instanceof A
告诉您a的动态类型是A类型还是A类的子类
更新2:
举例说明了这一点
public class PlayGround {
public static void main(String[] args) {
Animal a = new Dog();
System.out.print(a.name);// displays animal
System.out.print("\r\n");
a.MakeStaticSound();// displays static animal sound
System.out.print("\r\n");
a.MakeSound();// displays bow wow
}
}
class Animal {
public String name = "animal";
public void MakeSound() {
System.out.print("animal sound");
}
public static void MakeStaticSound() {
System.out.print("static animal sound");
}
}
class Dog extends Animal {
public String name = "dog";
public void MakeSound() {
System.out.print("bow wow");
}
public static void MakeStaticSound() {
System.out.print("static bow wow");
}
}
请注意,调用a.MakeStaticSound()的更可读和首选方法是Animal.MakeStaticSound()
标签:superclass,java,class,subclass,reference
来源: https://codeday.me/bug/20190824/1712693.html