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)
}
}