Search code examples
javanetbeansmethodsvirtual

Java Beginner Help Virtual Methods


I am a student in an OOP class, this is the first time I have ever actually worked with coding in Java and my head is spinning a bit.

My project is incomplete but only because I cannot seem to find out what my instructor is looking for, so hopefully you guys can give me some direction as to the right way to go.

The point of the assignment where I am confused is this statement.

Create a class called "Animal" with a virtual method displayInfo().

The following is my current code, I am using NetBeans 7.3

public class AnimalInfo {
    public class Animal{}
    public class Cow extends Animal{}
    public class Lion extends Animal{}
    public class Human extends Animal{}


    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        System.out.println("Please select an animal for a brief description of each:\n\nEnter 'A' for Cow.\nEnter 'B' for Lion.\nEnter 'C' for Human.\n\nEnter 'X' to Exit the application.");
        // TODO code application logic here
    }
}

What changes do I need to make to my implementation of public class Animal to comply with this displayInfo()?

Also, are JOptionPane's the only way to allow for user input? As I need to make the user's selections pull up the chosen animal's information (not yet implemented in the code above) I dont see anything allowing me to accept user input to be stored as a String.

Again, any help would be greatly appreciated. Thanks in advance!


Solution

  • Here is an example which would help you

    public abstract class Animal {
    
        public void displayInfo() {
            System.out.println("Im animal");
        }
    
    }
    
    public class Cow extends Animal {
        @Override
        public void displayInfo() {
            System.out.println("I am a Cow");
        }
    
    }
    
    public class Tiger extends Animal {
        @Override
        public void displayInfo() {
            System.out.println("I am a Tiger");
        }
    
    }
    
    public class Test {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            Animal animal = new Tiger();
            animal.displayInfo();
    
        }
    
    }
    

    Outpu:

     I am a Tiger