0

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);
Feeco
  • 3,872
  • 5
  • 25
  • 58

1 Answers1

4
abstract class Animal {

    void makeNoise() { System.out.println(noise()); }
    abstract String noise();
}

class Dog extends Animal {

    @Override
    String noise() { return "Woof!"; }

}

class Cat extends Animal {

    @Override
    String noise() { return "Meow!"; }

}

That's as good as you'll get.

Louis Wasserman
  • 172,699
  • 23
  • 307
  • 375
  • 4
    Too bad. You can't do anything like that in practice. Anything static and any kind of inheritance don't mix in any kind of useful way. – Louis Wasserman Nov 05 '17 at 00:26
  • Seems like this. [This comment](https://stackoverflow.com/a/1595000/4725496) describes it. – Feeco Nov 05 '17 at 00:28