Skip to content

Instantly share code, notes, and snippets.

@FrancescoJo
Last active June 27, 2019 01:01
Show Gist options
  • Save FrancescoJo/ac05e187bc655516351ea4dc2f7e0b6f to your computer and use it in GitHub Desktop.
Save FrancescoJo/ac05e187bc655516351ea4dc2f7e0b6f to your computer and use it in GitHub Desktop.
An example to demonstrate animal classification system in Java 1.8.x.
class Animal { }
class Reptile extends Animal { }
class Bird extends Animal { }
interface MobileLife {
// Every classes derived from this interface should implement common features on it.
void move(double displacement);
double getDistance();
};
interface Swimmer extends MobileLife {
default void swim() {
move(getSwimDistance());
}
double getSwimDistance();
};
interface Walker extends MobileLife {
default void walk() {
move(getWalkDistance());
}
double getWalkDistance();
}
class Duck extends Bird implements Swimmer, Walker {
/// {{{ Duplicate code could be found in class Turtle
private double distance = 0.0d;
@Override
public void move(double displacement) {
distance += displacement;
System.out.println("I moved " + distance + " metres.");
}
public double getDistance() {
return distance;
}
/// }}}
@Override
public double getWalkDistance() {
return 0.05D;
}
@Override
public double getSwimDistance() {
return 0.1D;
}
}
class Turtle extends Reptile implements Swimmer, Walker {
/// {{{ Duplicate code could be found in class Duck
private double distance = 0.0d;
@Override
public void move(double displacement) {
distance += displacement;
System.out.println("I moved " + distance + " metres.");
}
public double getDistance() {
return distance;
}
/// }}}
private int walkedTimes = 0;
@Override
public double getWalkDistance() {
walkTimes++;
if (walkedTimes % 10 == 0) {
return 0.001D;
} else {
return 0.0D;
}
}
@Override
public double getSwimDistance() {
return 0.5D;
}
};
class Main {
public static void main(String[] args) {
final Duck duck = new Duck();
duck.walk();
duck.swim();
final Turtle turtle = new Turtle();
turtle.swim();
for(int i = 0; i < 10; i++) {
turtle.walk();
}
}
}
/*
* Result:
* Duck says:
*
* I moved 0.05 metres.
* I moved 0.15000000000000002 metres.
*
* Turtle says:
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.5 metres.
* I moved 0.501 metres.
* I moved 0.501 metres.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment