isofiso
isofiso

Reputation: 1

Single Inheritance output question in java

I have a output question in java.


package javaapplication32;
class Animal {
    String name = "Animal";

    Animal() {
        System.out.println("Animal's name is: " + getName());
    }

    String getName() {
        return name;
    }
}

class Dog extends Animal {
    String name = "Dog";

    Dog() {
        System.out.println("Dog's name is: " + getName());
    }

    String getName() {
        return name;
    }
}

public class JavaApplication32 {
    public static void main(String[] args) {
        Dog dog = new Dog();
        
    }
}




The output of the code is:

Animal's name is: null

Dog's name is: Dog

And my question are that;

why does the 'getName();' method which is in the Animal constructor invoke the method of Class Dog and why didn't it return "Dog" ?

I expected the output as;

Animal's name is: Animal

Dog's name is: Dog

Upvotes: 0

Views: 76

Answers (1)

airsquared
airsquared

Reputation: 633

The getName() method in Dog overrides the getName() method in its superclass Animal, so no matter what class the code is in, if the object is a Dog, it will call getName() in Dog.

It prints Animal's name is: null because the constructor in the superclass is called before the fields in the subclass are initialized and the constructor in the subclass is called.

If you want it to print the value of the name variable in Dog before the instance is fully initialized, you can make the variable static (but this makes it no longer a class field and would apply to all instances of Dog).

Upvotes: 0

Related Questions