关于子类继承父类时,子类与父类有同名变量,当使用子类对象调用父类方法使用同名变量问题

首先在网上有这样一段代码
package test;
public class aaa {
public static void main(String[] args){
Son son = new Son();
son.minusOne();
System.out.println(son.testValue);
System.out.println(son.getSuperTestValue());
son.plusOne();
System.out.println(son.testValue);
System.out.println(son.getSuperTestValue());
}
}
class Father{
int testValue = 100;
public void minusOne(){
testValue--;
}
}
class Son extends Father{
int testValue = 0;
public void plusOne(){
testValue++;
}
public int getSuperTestValue(){
return super.testValue;
}
}
结果是
0
99
1
99
说明了当使用子类对象调用方法使用同名变量,是按照方法来判断使用哪一个变量,调用父类的方法,使用的是父类中的变量,调用子类的方法,使用的是子类中的变量

但是请看如下代码
public class fatherPanel extends JPanel {
protected BaseSendTextPanel inputText;
.....
public void newPaste()
{
inputText.paste();
}
.....
}

public class childPanel extends fatherPanel {
protected BaseSendTextPanel inputText;
.....
public void main()
{
KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,ActionEvent.CTRL_MASK, false);
// 重新注册粘贴事件
inputText.registerKeyboardAction(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent actionevent) {
newPaste();
}
}, "Paste", paste,JComponent.WHEN_FOCUSED);
}
.....
}

这段代码中,实际上在子类childPanel 中的inputText的ctrl+V事件中,调用的newPaste()中的inputText是子类的inputText,然而newPaste()明明是父类的方法,按照一开始那段说明,这里父类newPaste()中调用的inputText难道不应该是父类的变量吗?为什么它调用的是子类的变量?

代码没细看 我理解的意思是 子类和父类里有相同的方法。如果直接调用这个方法的话,默认是子类的 你需要调用父类的方法 用关键字 :super.父类方法 这样调用的就是父类的方法
温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-05-17
第一个demo中的getSuperTestValue()方法,有一个super关键字。指明了调用的是父类的属性。
相似回答