![](/img/trans.png)
[英]How child class object accesses parent class method or Data Member via extends keyword in Java
[英]Java implementation of this - calling a Parent class method to utilizing Child class data member
這個問題是關於實現決策 super
和this
在Java中。 考慮,
父類包含變量name
和方法getName()
public class Parent {
protected String name = "Parent";
protected String getName(){
return this.name;
}
}
Child類繼承Parent類,但有自己的name
變量
public class Child extends Parent {
protected String name = "Child";
protected void printNames() {
System.out.println("Parent: " + super.getName());
System.out.println("Child: " + this.getName());
}
public static void main(String[] args) {
Child c = new Child();
c.printNames();
}
}
輸出:
Parent: Parent
Child: Parent
從輸出中,我們可以看到: 當從具有super
上下文的Child類調用方法getName()
,它返回“Parent”,但是當使用this
上下文調用時,它再次返回“Parent”
如果該方法僅存在於Parent類中,但兩者中都存在具有相同訪問修飾符的數據成員,
為什么不應該來自Child類的this.getName()
返回“Child”,因為它is-a
getName()
Parent因此具有getName()
作為其方法
更新這個問題不是如何獲得印有“兒童”或壓倒一切的,其大約決定執行this
由Java核心團隊,它打算給他們。
字段不是overridable
方法,字段只能隱藏或不隱藏。 this
實際上指的是在當前Object
,其是類型的Parent
在該方法中Parent#getName()
使得其將得到的變量名稱的所定義的值Parent
在子類似或潛在父類而不是Child
。
這是一個簡單的代碼片段,顯示了這個想法:
Child child = new Child();
// Show the variable name of the class Child
System.out.println(child.name);
// Show the variable name of the class Parent which is what this.name
// does in the getName method
System.out.println(((Parent)child).name);
輸出:
Child
Parent
如果你想把'child'作為輸出你必須覆蓋getname()方法,否則它將被繼承,它將始終顯示'parent'作為輸出。
只需覆蓋Child類中的getName()
方法即可
@Override
protected String getName() {
return name;
}
如果您不想覆蓋getName()
方法,可以這樣做:
Child
構造函數中設置name
值,因為它是protected
屬性 不要在Child
類中重寫name
屬性
public class Child extends Parent { public Child() { super(); this.name = "Child"; } // ... }
您需要將getName()方法添加到子類。 現在,當您調用this.getName()時,將調用父版本,因為它未在子類中重寫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.