简体   繁体   中英

Error when extending superclass to subclass in Java - polymorphism

I'm currently tackling polymorphism on my java journey and I'm trying out these example codes in Eclipse. I just copied the codes but I'm really wondering why my codes wouldn't compile.

So I got three files: Example.java, Animals.java and Dog.java.

Example.java contains the main method:

public class Example {
    public static void main(String[] args) {
        Animal myDog = new Dog();
    }
}

Then I created two other classes for Animal and Dog as follows

Animal Class

public class Animal {

    public void makeNoise() {
    }

    public void eat(){
    }

    public void sleep() {   
    }

    public void roam() {

    }

}

Dog Class

public class Dog {

}

The way I understand it is that I can make Dog my subclass that extends the superclass Animal. But why wouldn't my codes compile?

Am I missing something in these codes?

Your Dog class doesnt extend animal class so this is invalid:

Animal myDog = new Dog();

you need to modify the class Dog in order to inherit the Animal Class

you achieve that doing:

public class Dog extends Animal{

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