0

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

isofiso
  • 1
  • 2
  • It's because per Java rules, the superclass constructor Animal() gets called really early on, even before Dog.name gets initialised to "Dog", so when Animal() calls getName(), which is overriden by Dog.getName(), it prints Dog.name which is not yet initialized (null). – invertedPanda Apr 20 '23 at 20:24

1 Answers1

0

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

airsquared
  • 571
  • 1
  • 8
  • 25
  • So it always depends on which class the dog is an instance of. right? – isofiso Apr 20 '23 at 20:22
  • @isofiso Yes, the `getName()` method that is called depends on which class it is an instance of. If you want it to be just an `Animal`, then you would have to create a `new Animal()`, not a `new Dog()`. – airsquared Apr 20 '23 at 20:30