JCB JCB - 5 months ago 6
Java Question

Difference between different ways in instantiating an object in Java

I have the code:

class Father{
String name="father";
void f(){System.out.print("father class");}
}

class Son extends Father{
String name = "son";
void f(){System.out.print("son class");}
void f2(){}
}

public class Test {

public static void main(String[] args) {
Father s = new Son();
System.out.println(s.name);// outputs father
s.f();// outputs "son class"
s.f2();// s does not have f2
}

}


My question is, what is the difference between doing Father s = new Father() or, Father s = new Son() or, Son s = new Son()?

As well, why does s.f2 in the example cause an error? Must Father implement f2()?

Answer

I think it is easier to explain with an animal example:

class Animal {

    void printName() {
        System.out.println("Animal");
    }
}
class Dog extends Animal{

    @Override
    void printName() {
        System.out.println("Dog");
    }
}
class Cat extends Animal{

    @Override
    void printName() {
        System.out.println("Cat");
    }

    void meow() {
        System.out.println("meow");
    }
}

When you extend classes, the child class can override parent's methods and can have its own methods. In my Animal example the generic Animal object can only give its name, but the Cat object can give its name and also meow. Obviously, the meow method is specific to Cat as we know that Dogs can't do meow and Animals in general.

When you do

Animal animal  = new Cat();

You actually create an instance of the Cat but use it as a general Animal. Thus, your animal instance only has methods which are available in the Animal class but the execution of the methods overridden by Cat class will be delegated to the Cat class. if you want to execute Cat's specific methods then you need to cast your Animal to the Cat

(Cat) animal.meow();

In your example to call f2() method you need to cast your father object to the son first

(Son)s.f2();