Felix Grund
Instructor @ UBC
Assume all mammals walk, eat, and make noises
public interface Mammal {
void walk();
void makeNoise();
void eat();
}
Assume all dogs walk and eat the same way
public class Dog implements Mammal {
@Override
public void walk() {
System.out.println("waaalk...");
}
@Override
public void eat() {
System.out.println("mmmmpf...");
}
}
@Override
public void makeNoise() {
System.out.println("NOT SURE"); // ???
}
But different dogs make completely different noises
public class Dog implements Mammal {
// ...
@Override
public void makeNoise() {
System.out.println("NOT SURE"); // ???
}
}
public class Poodle extends Dog {
}
"Not Sure"?
public class Dog implements Mammal {
// ...
@Override
public void makeNoise() {
System.out.println("NOT SURE");
}
}
public abstract class Dog implements Mammal {
// ...
@Override
public abstract void makeNoise();
}
public class Poodle extends Dog {
@Override
public void makeNoise() {
System.out.println("Wiiif wiiif");
}
}
OR (next level!)
public abstract class Dog implements Mammal {
}
public class Poodle extends Dog {
}
public abstract void bark();
@Override
public void makeNoise() {
bark();
}
@Override
public void bark() {
System.out.println("Wiiif wiiif");
}
Dog dog = new Dog();
Dog poodle = new Poodle();
Dog borderCollie = new BorderCollie();
Dog germanShepherd = new GermanShepherd();
dog.bark(); // Woof Woof (generic)
poodle.bark(); // Wiiif Wiiif
borderCollie.bark(); // Wuuuf Wuuuf
germanShepherd.bark(); // Waaaf Waaaf
public abstract class Dog {
// ...
abstract void bark();
abstract void bark(int times);
}
public class Poodle extends Dog {
@Override
public void bark() {
System.out.println("Wiiif wiiif");
}
@Override
public void bark(int times) {
for (int i = 0; i < times; i++) {
bark();
}
}
}
public abstract class Barista {
public void serveCoffee(){
greet();
giveCoffee();
sayGoodbye();
}
protected _________ void giveCoffee()
protected _________ void greet()
protected _________ void sayGoodbye()
}
public class HappyBarista {
// greet and say goodbye in a cheery way
}
public class GrumpyBarista {
// greet and say goodbye in a grumpy way
}
What methods should be abstract?
What methods should be implemented in HappyBarista and GrumpyBarista?
super
protected
method override
supertype
subtype
declared/apparent type
actual/instantiated type
method dispatch
method overload
By Felix Grund