I’m learning OOP in java and I’m trying to decide if I can/should use inheritance in this example. Do not pay attention to access modifiers and things like that.
There are two kind of pets:
- dogs (name, breed, age, owner)
- cats (name, breed, color, owner)
Dog.toString() should return "Name: name, Breed: breed, Age: age, Owner: owner"
Cat.toString() should return "Name: name, Breed: breed, Color: color, Owner: owner"
My question is: should I implement toString() in an abstract class and override in derived classes? How? I mean, there is only one field. I can’t see the gain.
So, I did:
abstract class Pet { String name; String breed; String owner; // getters setters public String toString() { return ???? } } class Dog extends Pet { int age; public String toString() { return String.format("Name: %s, Breed: %s, Age: %d, Owner: %s", name, breed, age, owner) } } class Cat extends Pet { String color; public String toString() { return String.format("Name: %s, Breed: %s, Color: %s, Owner: %s", name, breed, color, owner) } }
Advertisement
Answer
This is a situation where you could consider applying the Template Method design pattern. In this pattern, you define the reusable part of your method in the abstract class, and implement only the variable parts in the subclasses. For example:
abstract class Pet { // ... protected abstract String extra(); // Or, return the empty String public final String toString() { return String.format("Name: %s, Breed: %s, %s, Owner: %s", name, breed, extra(), owner); } }
In your subclasses:
class Dog extends Pet { int age; public String extra() { return String.format("Age: %d"); } }