Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a child to the parent issue in Java

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?

like image 665
MY PC Avatar asked Mar 15 '26 20:03

MY PC


1 Answers

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

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

((TYPE)(EXPRESSION|VARIABLE))
like image 51
Andrew Tobilko Avatar answered Mar 17 '26 10:03

Andrew Tobilko