Skip to content

Instantly share code, notes, and snippets.

@speters33w
Created October 10, 2023 01:26
Show Gist options
  • Save speters33w/3311ac225cd1b9897740073a027ec3eb to your computer and use it in GitHub Desktop.
Save speters33w/3311ac225cd1b9897740073a027ec3eb to your computer and use it in GitHub Desktop.
A silly inheritance and polymorphism example.
public class DogHuman extends SuperHuman {
public DogHuman(String name, int age) {
super(name, age);
}
@Override
public String greet() {
return "Woof woof, woof woof, woof woof, woof woof, woof woof";
}
/*
Returns the DogHuman's age in dog years.
*/
@Override
public int getAge() {
return super.getAge() * 15;
}
}
import java.util.Random;
public class HumanRunner {
public static void main(String[] args) {
Random random = new Random();
SuperHuman superHuman = new SuperHuman("John", random.nextInt(100) + 1);
SubHuman subHuman = new SubHuman("Glug", random.nextInt(100) + 1);
int dogHumanAge = random.nextInt(7) +1;
DogHuman dogHuman = new DogHuman("Dog", dogHumanAge);
System.out.printf("The human says: \"%s\"%n", superHuman.greet());
System.out.printf("%s says: \"%s\"%n", subHuman.getName(), subHuman.greet());
System.out.printf("The dog says: \"%s\".%n",dogHuman.greet());
System.out.printf("%s is %d years old, but in dog years that's %d.%n",
dogHuman.getName(), dogHumanAge, dogHuman.getAge());
}
}
public class SubHuman extends SuperHuman{
public SubHuman(String name, int age) {
super(name, age);
}
@Override
public String greet() {
return "Grrrow, ug slrowl slurp";
}
}
public class SuperHuman {
private String name;
private int age;
public SuperHuman(String name, int age) {
this.name = name;
this.age = age;
}
protected String getName() {
return this.name;
}
protected int getAge() {
return this.age;
}
public String greet() {
return String.format("Hello, my name is %s. I am %d years old.", this.name, this.age);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment