cooltogo cooltogo - 1 year ago 29
Java Question

Difficulty with the concept of java inheritance and overriding

The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass.

class Animal {
public void move() {
System.out.println("Animals can move");

class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
public void bark() {
System.out.println("Dogs can bark");

public class TestDog {

public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class

output: error: cannot find symbol
symbol: method bark()
location: variable b of type Animal
1 error

What I do not understand here is why is the object 'b' able to access the Dog.move() and not Dog.bark() because the statement mentioned above says it can access only the members of the superclass and not the subclass.Following this logic the output of b.move() should be "Animals can move" and not "Dogs can walk and run".But that is not case.Can anyone help me with this?Thanks in advance!

Answer Source

Congratulations - you just discovered polymorphism.

In Java the classes are bound dynamically. That is if you are invoking a method the implementation of the object is invoked (in your case the Dog) and not the method of the reference type (in your case the Animal).

This allows overwriting methods and replace or fulfill their implementation.

On the other hand, you can only access methods that are available in the type you are referencing, not the implementing type (in your case the Animal). To invoke the methods of the instance, you would have to use it as the reference type (in your case the Dog).