java - Java多态中的成员访问特性
问题描述
public class A {
public int a = 10;
public void show() {
}
}
public class B extends A{
public int a = 20;
public int b = 10;
@Override
public void show() {
System.out.println(this.a);
}
public static void main(String[] args) {
A a = new B();
a.show();
System.out.println(a.a);
}
}
看上面的代码,我使用父class A
引用指向子class B object (A a = new B())
,但是当我a.a(System.out.println(a.a))
在main方法中打印时,它打印是因为成员变量a在父中10
被赋值了一个值。但是当我在子类中重写的方法中打印时,方法打印,它打印,我很困惑。我认为结果应该是一样的。可以看到输出如下图:</p>
10
class A
this.a(System.out.println(this.a))
show
show
this.a (System.out.println(this.a))
20
20
10
提前致谢!
解决方案
在java中,只有方法被覆盖,而不是变量。因此,父类的变量不会被子类的变量覆盖。这是Java中的设计决策。其中一个问题是父类方法可以执行而不必担心子类变量......即它有助于not breaking parent classes code
......
一个例子可能如下所示:
public class Parent {
String someVar; // note this: it is "String" type
String getSomeVar() {
}
}
public class Child extends Parent {
int someVar; // same name but different type, this would break the code if
// java permit "variable overriding" feature
}
可以清楚的看到,parent 的 type 和 child 的 type 是不一样的。我想,您现在可以理解为什么变量覆盖会很危险......
更新:
@helloWorld,在阅读了您发表的最后一条评论后,您似乎误解了overriding
.
特别是,我为你准备了一个例子。阅读以下带有注释的代码:
class A {
public int a = 10;
public void show () {
System.out.println("Inside A: " + this.a);
}
}
class B extends A {
public int a = 20;
public int b = 10;
@Override
public void show() {
System.out.println("Inside B: " + this.a);
}
}
B b = new B();
A a = b;
b.show(); // prints "Inside B: 20", it should print "20", so it's okay
a.show(); // prints "Inside B: 20", so, method in 'A' is overrided by class 'B', cause, in normal definition it should print "10"
System.out.println("value of b.a: " + b.a); // prints "value of b.a: 20", it should print '20', so it's okay
System.out.println("value of a.a: " + a.a); // prints "value of a.a: 10", it is not overrided by class 'B', but notice 'a.show()' method was overrided
所以,我想,你已经明白了,覆盖意味着:当使用something(a method/variable)
byparent/super class's reference
但获得在child class's
whileparent/super
类的实现中定义的行为时particular method/variable
,被称为覆盖......
你也可以阅读这个。
关于this
:
this
必然an object
。而且它总是access
只用于那个特定的,class's scope
即variables/methods
在 that 中声明的class
。因此,要在您parent
内部访问,child
您需要使用super
.
推荐阅读
- javascript - 如何在不同的输入中从模态中获取值
- c# - 将 XML 中的多项选择元素序列化为 C#
- c# - SpecFlow 未发现测试或我收到错误消息
- html - 如何使用基于 JSON 的下拉菜单来过滤 xml 源?
- google-sheets - IMPORTXML 在 NCBI 网站的特定页面上返回 #N/A - 受刮擦保护?
- reactjs - React 中的状态,如何保存原始的`?
- typescript - 扩展日期类型表示未找到函数
- carrierwave - Gem Carrierwave 不允许上传应用程序/八位字节流文件
- javascript - 如何在打字稿上定义自定义属性并将其与匿名对象一起使用?
- vb.net - vb.net datagridview中的双数据