簡體   English   中英

Java的實現 - 調用Parent類方法來利用Child類數據成員

[英]Java implementation of this - calling a Parent class method to utilizing Child class data member

這個問題是關於實現決策 superthis在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM