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

public String toString() {
   return super.toString() + ...

The superclass toString is called because the subclass's toString calls it ( super.toString() )

1. Is it default behavior?
2. and is it only applicable on toString()?
3. and does parent class call its parent class?

1. No, it;s something that was coded explicitly in this program
2. No , you can do it for any method you override
3. Only if it does the same thing (ie use the super keyword to call the method from the superclass).

This is how it works:
Dog overrides Animal's toString() method (and Animal overrides Object's toString()).
When you call aDog.toString() the toString() in the Dog class is executed.
As part of the code of Dog's toString() the programmer has coded super.toString() That tells Java to execute the toString from the superclass (ie Animal)

Edited 4 Years Ago by JamesCherrill: n/a

This article has been dead for over six months. Start a new discussion instead.