簡體   English   中英

Java:如何在主類中調用方法,而該方法在另一個類中,該類擴展了抽象類

[英]Java: How to call upon a method in a main class where the method is in another class which extends an abstract class

我被要求創建一個主要方法,該方法允許我創建狼對象,鸚鵡對象和犀牛對象。我為這些動物中的每一個都創建了類,並且它們擴展了包含抽象方法makeNoise()的抽象類動物。 我已經在我的犀牛,鸚鵡和狼類中實現了這種抽象方法,並且該方法包含System.out.println函數以及與這些動物中的每一個相關的噪聲。 例如,我的鸚鵡類(擴展了動物)包含一個方法makeNoise(),該方法打印出“ squawk”。

我被要求證明我可以在主類中為我的每個動物對象調用此makeNoise方法,該如何進行呢?

public class Main() {
     Wolf myWolf = new Wolf();
     //I want my wolf to make a noise here

     Parrot myParrot = new Parrot();
     //I want my parrot to make a noise here

     Rhino myRhino = new Rhino();
     //I want my rhino to make a noise here
}

您的代碼甚至不是有效的Java,您正在混合類和方法的語義(最有可能是其背后的概念)。

您的班級將需要一個main方法來使您的班級可以從外部執行。

public class Main {
     Wolf myWolf = new Wolf();
     Parrot myParrot = new Parrot();
     Rhino myRhino = new Rhino();

     public static void main(String[] args) {
         myWolf.makeNoise();
         myParrot.makeNoise();
         myRhino.makeNoise();
     }
}
public class Main
{
    Animal myWolf = new Wolf();
    Animal myParrot = new Parrot();
    Animal myRhino = new Rhino();

    public void someMethod() {
        System.out.println(myWolf.makeNoise());
        System.out.println(myParrot.makeNoise());
        System.out.println(myRhino.makeNoise());
    }
}

因為Animal是具有抽象方法makeNoise()的抽象類,所以可以使用抽象類本身並將其實現該方法的任何子類分配給它。 不同的分配證明了多態性,其中makeNoise()可以具有不同的解釋。 因此,將Parrot更改為Rhino將導致makeNoise()的不同實現。

暫無
暫無

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

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