Kal*_*iMa 1 java oop inheritance superclass
我正在输出
SubClass subClass = new SubClass(4);
System.out.println(subClass.getVal());
Run Code Online (Sandbox Code Playgroud)
有了这两个类:
public class SuperClass {
public int x = 99;
public int superClassMethod() {
return -1;
}
}
public class SubClass extends SuperClass {
public int x;
public SubClass(int value) {
x = value;
}
public int getVal() {
return x;
}
}
Run Code Online (Sandbox Code Playgroud)
这4
按预期输出.但是,让我说我x = value
在SubClass
构造函数中注释掉了这一行.为什么输出0
(我假设未启动的变量的默认值)而不是99
从超类继承?
如果我改变return x
到return superClassMethod();
它似乎正确地拉-1
从超.那么为什么方法而不是变量呢?
当变量具有来自不同范围的冲突名称时,它总是使用最近范围内的变量,即使它尚未设置为任何范围.
要区分其他范围中的变量,请在变量前加上this
或super
:
public class SuperClass {
protected int x;
}
public class SubClass extends SuperClass {
private int x;
public SubClass(int x) {
x = 2; // sets the parameter variable
this.x = 2; // sets the instance variable
super.x = 2; // sets the super class' instance variable
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
112 次 |
最近记录: |