簡體   English   中英

Java:子類調用父類方法

[英]Java: subclass calling parent class methods

我有一個父類Shape和一個Rectangle子類,在父類Shape中有一個稱為Output的方法 如何在子類中調用父類方法Output

家長班

public class Shape {
  public int edge;
  public Shape(int Gedge) {
    edge=Gedge;
  }
  public void Output() {
    System.out.println("This shape has "+edge+" eges");
  }
}

子類:

public class Rectangle extends Shape {
  public int edge, length, width;
  public Rectangle(int Gedge, int Glength, int Gwidth) {
    super (Gedge);
    edge=Gedge;
    length=Glength;
    width=Gwidth;
  }
  public void Output1() {
    //I want to call the parent class Method "Output" here.
    System.out.println("The Area is "+length*width);
}
  public static void main (String [] args) {
    Rectangle A1=new Rectangle(4,3,5);
      A1.Output1();
}
}

如果我現在運行此代碼,則輸出為The Area是15 ,但是我想在Shape中調用Output方法,因此理想情況下它會打印

該形狀有4個邊緣

面積是15

感謝幫助。 謝謝

只需調用方法:

public void Output1() 
{
    Output();
    System.out.println("The Area is "+length*width);
}

不需要super關鍵字,因為您不會調用被Output1方法覆蓋的基類的方法。 您正在調用其他方法。

我認為在您的示例中,形狀必須是接口(必須使用area()方法和(Rect,Square ..)方法來實現。回到您的問題,因為那是在您的父類中,輸出是公共的,您可以在子類中執行以下操作: super.Output();

正如其他人已經回答了這個問題(調用super.Output()或只是調用Output()都是正確的)一樣,我將嘗試更加清楚地說明這兩者為何正確(這主要是由於您的命名約定) 。

當類之間具有父子關系時,如下所示:

class A {
    public void doStuff(){
        System.out.println("Doing A Stuff!");
    }
}
class B extends A {
    public void doStuff(){
        System.out.println("Doing B Stuff!");
    }
}

您正在執行的操作將覆蓋doStuff方法。 該行為將如下所示:

A a = new B(); // A is the parent type of a, B is the actual type.
a.doStuff(); // prints "Doing B stuff!"

在Java中重寫時,該方法必須具有完全相同的名稱,參數列表(以相同的順序)和返回類型。 因此,在您的示例中,Output1不是輸出的替代。 這就是為什么您實際上可以在子類中的任何位置調用Output()而不需要'super'關鍵字的原因。 如果要重構代碼以使兩個方法具有相同的簽名,那么可以,調用父類行為的唯一方法是在覆蓋方法中調用super.Output()。 實際上,如果您隨后以以下方式編寫了子類B,則對doStuff的調用將是遞歸調用,並且該方法將遞歸直到遇到堆棧溢出(因此,您需要使用super.doStuff()):

class B extends A {
    public void doStuff(){

        doStuff(); // BAD CODE!! Use super.doStuff() here instead!

        System.out.println("Doing B Stuff!");
    }
}

您可以確保調用超類的方法的另一種方法是使用超類型的實際類型實例化該對象,但隨后您將失去子類的所有功能:

A a = new A(); //both parent type and actual type of a is A
a.doStuff(); // prints "Doing A stuff!" (can't print "Doing B Stuff!")

同樣,如前所述,您應該檢查一下這個問題 ,它將使您朝着正式的Java風格指南和約定的方向發展。 關於代碼的一些快速注意事項是缺少局部變量的小寫駝峰(A1應該為a1)和方法(Output()應該為output())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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