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

Recommended Answers

All 5 Replies

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)

Thanks bro I did not read super.toString()
Thank you very much.

You can mark this "solved" now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.