Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
in the example below when i call the foo method with p it gets the one in child class but when i access the num variable it gets the one in parent class, so is the member type based on the reference variable type or what object it points to ?

Java
public class Main {

    public static void main(String[] args) {
    Parent p=new Child();
        System.out.println(p.num);
        p.foo();

    }

}


class Parent {
    public int num = 10;

    void foo() {
        System.out.println("Foo in parent");
    }
}


class Child extends Parent {
    public int num = 100;
    @Override
    void foo() {
        System.out.println("Foo in Child");
    }
}


What I have tried:

i don't what to fill in here so this is just random, sorry !
Posted
Updated 19-Apr-19 9:33am

1 solution

You got an "override" for foo; but not num; and child is cast as a "parent"; so it goes for parent.num.

Those are the differences.
 
Share this answer
 
Comments
hiwa doski 19-Apr-19 15:44pm    
okay thanks, but another question let's say child class contains method bar() if the reference variable of parent class point to the child object, and that child object contain the bar() method then why we can't call it with parent reference?
[no name] 19-Apr-19 19:06pm    
By "casting" child to parent, you limit child to only the members of "parent". It's a "contract" saying this object will at least support ONLY parent behavior, and nothing else (and the "compiler" respects this, even though we may sometimes be able to trick it).

While cast as parent, it's still a "child" after all and can (apparently) bring the override into play.

The override makes sense when you consider that a parent method can be virtual or abstract (i.e. a "stub") and the override must be honored to avoid a "not implemented" exception.
hiwa doski 24-Apr-19 8:29am    
explained very well, thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900