class Animal {
private String type;
Animal theAnimal = null; // Declare a variable of type Animal
public Animal(String aType) {
type = new String(aType);
}
public String toString() {
return "This is a " + type;
}
}
class Dog extends Animal{
private String name; // Name of a Dog
private String breed; // Dog breed
public Dog(String aName) {
super("Dog"); // Call the base constructor
name = aName; // Supplied name
breed = "Unknown"; // Default breed value
}
public Dog(String aName, String aBreed) {
super("Dog"); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
// Present a dog’s details as a string
public String toString() {
return super.toString() + "\nIt’s " + name + " the " + breed;
}
}
public class TestDerived {
public static void main(String[] args) {
Dog aDog = new Dog("Fido", "Chihuahua"); // Create a dog
System.out.println(aDog); // Let’s hear about it
}
}
Output:
This is a Dog
It’s Fido the Chihuahua
I want to ask is that why parent class(Animal)'s method toString() is being called even it is overridden in child class(Dog). Thanks