简体   繁体   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

I have been asked to create a main method that allows me to create a wolf object, parrot object and rhino object, I have created classes for each of these animals and they extend the abstract class animal which contains an abstract method makeNoise(). 我被要求创建一个主要方法,该方法允许我创建狼对象,鹦鹉对象和犀牛对象。我为这些动物中的每一个都创建了类,并且它们扩展了包含抽象方法makeNoise()的抽象类动物。 I have implemented this abstract method within my rhino, parrot and wolf classes and the method contains a System.out.println function and the noise associated with each of these animals. 我已经在我的犀牛,鹦鹉和狼类中实现了这种抽象方法,并且该方法包含System.out.println函数以及与这些动物中的每一个相关的噪声。 For example my parrot class(which extends animal) contains a method makeNoise() which prints out "squawk". 例如,我的鹦鹉类(扩展了动物)包含一个方法makeNoise(),该方法打印出“ squawk”。

I have been asked to demonstrate that I can call upon this makeNoise method for each of my animal objects in the main class, how do I go about doing this? 我被要求证明我可以在主类中为我的每个动物对象调用此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
}

Your code is not even valid Java, you're mixing class and method semantics (and, most likely, the concepts behind them). 您的代码甚至不是有效的Java,您正在混合类和方法的语义(最有可能是其背后的概念)。

Your class will need a main method to make your class executable from the outside. 您的班级将需要一个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());
    }
}

Because Animal is an abstract class which has the abstract method makeNoise() , it's fine to use the abstract class itself and allocate it any of its child classes which implements the said method. 因为Animal是具有抽象方法makeNoise()的抽象类,所以可以使用抽象类本身并将其实现该方法的任何子类分配给它。 The different allocations demonstrates polymorphism wherein makeNoise() can have varying interpretations. 不同的分配证明了多态性,其中makeNoise()可以具有不同的解释。 Changing Parrot to Rhino will thus result in a different implementatio of makeNoise() . 因此,将Parrot更改为Rhino将导致makeNoise()的不同实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM