2

I am using a Inheritance concept here. I have extended class A(Superclass) into class B(Subclass). And I have created an object of a subclass and by using that object I have called add() method. But it is printing a value 5(Super Class). Why it didn't take subclass's value which is 10 ?

class A{
    int a=5;

    public void add(){
        System.out.println(a);
    }
}
class B extends A{
    int a=10;


}
public class InheritExample {

    public static void main(String args[]){
        B b1=new B();
        b1.add();
    }
}

Help Appreciated. Thanks.

Vipul Dhage
  • 85
  • 1
  • 1
  • 5

1 Answers1

2

There's no overriding of instance variables. Overriding only works on instance methods. Therefore, the method add of class A has access only to the a variable declared in A, even if you call that method for an instance of class B.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • but if we do `System.out.println(new B().a);` it prints `10` and if we print `System.out.println(this.a);` it prints `5` but `this` is `B's` object check https://gist.github.com/anonymous/8e16a17ae260e36a1bee . If both the cases have same `B's` object then why outputs different? – codegasmer Oct 24 '15 at 09:35
  • 1
    @codegasmer `B` has two instance variables called `a`. One if declared in `B` class and hides the one declared in `A` class. A method of class `A` doesn't know about `a` of class `B`. On the other hand, a method of class `B` only sees `a` of class `B`. – Eran Oct 24 '15 at 09:40
  • When you say new B().a you're not using a super class as a reference holder. That is., calling new B().a is not the same as A o = new B(); o.a; this refers to the instance where it is used, so where you use this matters – Cybermonk Oct 24 '15 at 09:43