0

bb refers Derived class, when i call show() method, but when i print bb.b - is prints Base class property . Why is this happening?

class Base {
    int b=10;
    public void show() {

        System.out.println("Base show() called");

    }
}



class Derived extends Base {

    int b=20;
    public void show() {

        System.out.println("Derived show() called");

    }

}

public class MainClass {

    public static void main(String[] args) {

        Base bb = new Derived();;

        bb.show();
        System.out.println(bb.b);

    }

}

output :

Derived show() called

10

3
  • 1
    Overriding only exists for methods. Commented Dec 4, 2017 at 10:42
  • 2
    No, it's not.It's hiding. Commented Dec 4, 2017 at 10:47
  • 1
    It's not overriding. In that case you're using a Derived variable to print a Derived field. Commented Dec 4, 2017 at 10:47

4 Answers 4

2

While you declare your variable as a Base obj (i.e. Base bb = new Derived();), that does not mean your b object is no longer an instance of Derived (verify this with b instanceof Derived).

This is called hiding and is similar to what people usually do when declaring variables that might later change implementation for example private List<String> someList = new ArrayList<>();. In more technical terms: it's a way of decoupling your code from a specific implementation.

As to why b is 10 (the Base class's value) and not 20: that is because you are explicitly referring to b value in Base class (as mentioned by Timothy Truckle's answer). If you were to explicitly cast your b object back to Derived type, you will see 20 being printed instead:

System.out.println(((Derived)b).b);
Sign up to request clarification or add additional context in comments.

Comments

0

You output is 10because you explicitly access variable b in class Base.

Beside the technical aspect doing so this is not OOP since it violates the most important OO principle: information hiding / encapsulation.

Comments

0

This is because the compiler implements special run time polymorphism for methods only. This is also called method overriding.

For variables, the value will always be from the Base class, because that is the type of bb object regardless of the class with with it is instantiated.

Comments

0

There is no polymorphism for fields in Java.

Variables are resolved compile-time, methods run-time. so always Base Class variables (not child’s inherited variables) will be accessed.

So whenever upcasting happens always remember

  1. Base Class variables will be accessed.

  2. Sub Class methods(overridden methods if overriding happened else inherited methods as it is from parent) will be called.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.