Skip to content

Instantly share code, notes, and snippets.

@makiftutuncu
Last active December 21, 2019 22:10
Show Gist options
  • Save makiftutuncu/8d1b10f7fb3dd35416fc9f982b21feda to your computer and use it in GitHub Desktop.
Save makiftutuncu/8d1b10f7fb3dd35416fc9f982b21feda to your computer and use it in GitHub Desktop.
A cliché example of interface vs. abstract class in Java
// Behavior of talking
interface Talks {
void talk(String what);
}
// Behavior of making sound
interface MakesSound {
void makeSound(String what);
}
// Behavior of moving
interface Moves {
void move(String where);
}
// Abstract type of an organism which has a name and can describe itself
abstract class Organism {
public String name;
public abstract String describe();
}
// Abstract type of an animal which is an organism, which has a kind, which can describe itself, make sound and move
abstract class Animal extends Organism implements MakesSound, Moves {
public String kind;
}
// Abstract type of a person which is an organism, who has an age, who can describe himself/herself, talk and move
abstract class Person extends Organism implements Talks, Moves {
public int age;
}
// Concerete type for a cat which is an animal -therefore an organism-, which can describe itself, make sound and move
class Cat extends Animal {
public Cat(String name, String kind) {
this.name = name;
this.kind = kind;
}
@Override public String describe() {
return kind + " cat named " + name;
}
@Override public void makeSound(String what) {
System.out.println(describe() " meows " + what);
}
@Override public void move(String where) {
System.out.println(describe() + " moves to " + where);
}
}
// Concerete type for a doctor which is a person -therefore an organism-, who has an age, who can describe himself/herself, talk and move
class Doctor extends Person {
public Doctor(String name, int age) {
this.name = name;
this.age = age;
}
@Override public String describe() {
return "" + age + " year(s) old doctor named " + name;
}
@Override public void talk(String what) {
System.out.println(describe() " talks and says " + what);
}
@Override public void move(String where) {
System.out.println(describe() + " moves to " + where);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment