简体   繁体   中英

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(). 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. For example my parrot class(which extends animal) contains a method makeNoise() which prints out "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?

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).

Your class will need a main method to make your class executable from the outside.

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. The different allocations demonstrates polymorphism wherein makeNoise() can have varying interpretations. Changing Parrot to Rhino will thus result in a different implementatio of makeNoise() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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