2010-11-15 65 views
7

我有一個java初學者問題: Parent.print()在控制檯中打印「hallo」, 但Child.print()打印「hallo」。 我以爲它必須打印「孩子」。 我該如何解決這個問題?Java擴展示例

public class Parent { 

    private String output = "hallo"; 

    public void print() { 
     System.out.println(output); 
    } 

} 

public class Child extends Parent { 

    private String output = "child"; 

} 

回答

7

目前你有兩個獨立的變量,並在Parent代碼只知道Parent.output。您需要將Parent.output的值設置爲「孩子」。例如:

public class Parent { 

    private String output = "hallo"; 

    protected void setOutput(String output) { 
    this.output = output; 
    } 

    public void print() { 
    System.out.println(output); 
    } 
} 

public class Child extends Parent { 
    public Child() { 
    setOutput("child"); 
    } 
} 

另一種辦法是給父類的構造函數歷時所需的輸出:

public class Parent { 
    private String output; 

    public Parent(String output) { 
    this.output = output; 
    } 

    public Parent() { 
    this("hallo"); 
    } 

    public void print() { 
    System.out.println(output); 
    } 
} 

public class Child extends Parent { 
    public Child() { 
    super("child"); 
    } 
} 

這真的取決於你想要做什麼。

+0

OK,它的工作原理,但我不不明白爲什麼我的企圖是不能工作.... – 2010-11-15 19:39:19

+0

@馬丁:因爲你正在創建一個完全獨立的變量,並在'Child'中設置* that *的值。 「Parent」類不知道「Child」中的變量。 – 2010-11-15 19:58:57

3

Child沒有獲得Parentoutput實例變量,因爲它是private。你需要做的是使它protectedChild的構造函數集output"child"

換句話說,兩個output變量是不同的。

你也可以這樣做,如果你改變輸出爲protectedParent

public void print(){ 
    output = "child" 
    super.print(); 
} 
0

孩子不打印「孩子」的原因是,在java繼承中,只有方法是繼承的,而不是字段。變量output不會被孩子覆蓋。

你可以做這樣的:

public class Parent { 
    private String parentOutput = "hallo"; 

    String getOutput() { 
     return output; 
    } 

    public void print() { 
     System.out.println(getOutput()); 
    } 
} 

public class Child extends Parent { 
    private String childOutput = "child"; 

    String getOutput() { 
     return output; 
    } 
} 

此外,字符串變量並不需要是不同的名字,但我這樣做是這裏的清晰度。

另一個更可讀的方式將做到這一點:

public class Parent { 
    protected String output; 

    public Parent() { 
     output = "hallo"; 
    } 

    public void print() { 
     System.out.println(output); 
    } 
} 

public class Child extends Parent { 
    public Child() { 
     output = "child"; 
    } 
} 

在這個例子中,變量爲protected,這意味着它可以從父母和孩子都被讀取。類的構造函數將變量設置爲期望的值。這樣你只能實現一次打印功能,並且不需要重複的重寫方法。

0

當我試圖找出extend關鍵字時,我使用了兩個類。我希望這也能幫助你理解基本的想法。

Parent.java

public class Parent { 
    private int a1; 
    private int b1; 


    public Parent(int a, int b){ 
     this.a1 = a; 
     this.b1 = b; 
    } 

    public void print() { 
     System.out.println("a1= " + this.a1 + " b1= " + this.b1); 
    } 

} 

Child.java

public class Child extends Parent { 
     public Child(int c1, int d1){ 
     super(c1,d1); 
    } 

    public static void main(String[] args) { 
     Parent pa = new Parent(1,2); 
     pa.print(); 
     Child ch = new Child(5,6); 
     ch.print(); 
    } 

}