0

Parent class

class Animal {
    public void sound() {
        System.out.println("Grr");
    }
}

Child class

class Dog extends Animal {
    public void sound() {
        System.out.println("Woof");
    }
}

Calling class

class Callings {
    public static void main(String args[]) {
        Animal a = new Dog();
        a.sound();
    }
}

Output is - "Woof"

My concern is--> I have read till now that if we use the parent class reference and point to object to child class then using the reference of parent class we can only access the data members and methods of the parent class only, if this is true then output of above code should be "Grr". But the output is "Woof" can any one explain why.

seenukarthi
  • 8,241
  • 10
  • 47
  • 68

2 Answers2

1

Even you are creating and object for Animal but the instance is type of Dog, you can create an instance of a child class and assign to the type of parent.

When you call a method, it should be defined in the parent class and if it is overridden in child then the child method will be called else the parent's method will be called.

You can check the type of the instance by printing the class type of the instance a by using System.out.println(a.getClass().getName()); which will print Dog

seenukarthi
  • 8,241
  • 10
  • 47
  • 68
0

Dog knows it is a Dog, even if you call it an Animal.

Check this question for more details.

vszholobov
  • 2,133
  • 1
  • 8
  • 23