Casting a child to the parent issue in Java

Viewed 54
class Parent {
    int i = 60;
}

class Child extends Parent {
    int i = 70;
}

class Main {

    public static void main(String[] args) {
        Child c = new Child();
        Parent p = new Parent();

        System.out.println((Parent c).i);
    }

}

Here I want to print a Parent class variable (i.e. i = 60) with the help of a Child class object. How can I do that?

3 Answers
System.out.println(((Parent) c).i);

The simplified template for casting an EXPRESSION or a VARIABLE to a TYPE is:

((TYPE)(EXPRESSION|VARIABLE))

Here is what you need

class Parent{
    int i = 60;
}

class Child extends Parent{
    int i = 70;
}

class TreeMap {

    public static void main(String[] args) {
        Child c = new Child();
        Parent p = new Parent();

        System.out.println(((Parent) c).i);
    }

}

You can write:

System.out.println(((Parent)c).i);
Related