java 类似ref_java – 指向子类对象的超类ref的类类型是什么?

我有以下代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值