Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Overriding with Inheritance

As I can understand here 'a1' reffed to a class B object which has 'a=200' as an attribute. Therefore I expected program will print 200. But why does this program prints 100 instead of 200?

    class A{
        int a=100;
    }

    class B extends A{
        int a=200;

    }

    class Demo{
        public static void main(String args[]){
            A a1=new B(); 
            System.out.println("a : "+a1.a); //Prints 100  
        }
    }
like image 846
amal Avatar asked Dec 15 '25 12:12

amal


1 Answers

By declaring a field in class B that has the same name as a field in its parent class A, you are essentially hiding that field. However, field access on a variable is done based on that variable's declared/static type.

In other words, fields are not polymorphic entities like methods are.

In this case, the variable a1 is declared as type A. The field accessed will therefore be the one in the parent class, A.

like image 116
Sotirios Delimanolis Avatar answered Dec 17 '25 02:12

Sotirios Delimanolis