-
-
Save sleepynate/d1fcb7a6015a2a035267d4e9c8fc3d94 to your computer and use it in GitHub Desktop.
An example of inheritance and polymorphism in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class Animal { | |
private String name; | |
public Animal(String name) { | |
this.name = name; | |
} | |
public String speak() { | |
return name + " says " + sound(); | |
} | |
public abstract String sound(); | |
} | |
class Cow extends Animal { | |
public Cow(String name) { | |
super(name); | |
} | |
@Override public String sound() { | |
return "moooooo"; | |
} | |
} | |
class Horse extends Animal { | |
public Horse(String name) { | |
super(name); | |
} | |
@Override public String sound() { | |
return "neigh"; | |
} | |
} | |
class Sheep extends Animal { | |
public Sheep(String name) { | |
super(name); | |
} | |
@Override public String sound() { | |
return "baaaa"; | |
} | |
} | |
public class AnimalDemo { | |
public static void main(String[] args) { | |
Animal h = new Horse("CJ"); | |
System.out.println(h.speak()); | |
Animal c = new Cow("Bessie"); | |
System.out.println(c.speak()); | |
System.out.println(new Sheep("Little Lamb").speak()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment