Imagine a simple hierarchy:
abstract class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
I want to implement abstract method makeNoise
, so that Dog
could override it to print Woof!
and Cat
could override it to print Meow!
.
I wrote the following code:
abstract class Animal {
abstract void makeNoise();
}
class Dog extends Animal {
@Override
void makeNoise() {
System.out.println("Woof!");
}
}
class Cat extends Animal {
@Override
void makeNoise() {
System.out.println("Meow!");
}
}
But I don't like it. I repeat sout
in overriden methods.
I would like to create an abstract final static
variable named SOUND
in Animal
and override it in the children:
abstract class Animal {
abstract static final String SOUND;
void makeNoise() {
System.out.println(SOUND);
}
}
class Dog extends Animal {
static final String SOUND = "Woof!";
}
class Cat extends Animal {
static final String SOUND = "Meow!";
}
But that code obviously doesn't work. But is it a way to create a logic such like this, so I can could create the following code:
new Dog().makeNoise(); // Woof!
new Cat().makeNoise(); // Meow!
UPDATE
Besides makeNoise
I also want to get access to a sound statically, so that I can also write the following code:
System.out.println("Dog says: " + Dog.SOUND);
System.out.println("Cat says: " + Cat.SOUND);