46

See my code below, in which the method print is overridden but variable a is not. Why is it allowed to declare duplicate variables in a subclass?

class B {
    int a = 10;
    public void print() {
        System.out.println("inside B superclass");
    }
}

class C extends B {
    int a = 20;
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C();
        b.print(); // prints: inside C subclass
        System.out.println(b.a); // prints superclass variable value 10
    }
}
4

7 Answers 7

55

Why instance variable of a superclass is not overridden in subclass method see my code below ...

Because instance variables CANNOT be overridden in Java. In Java, only methods can be overridden.

When you declare a field with the same name as an existing field in a superclass, the new field hides the existing field. The existing field from the superclass is still present in the subclass, and can even be used ... subject to the normal Java access rules.

(In your example, an instance of C has two distinct fields called a, containing distinct values.)


Because instance variables CANNOT be overridden in Java, but why? why is it done in this manner in Java? What's the reason?

Why did they design it that way?

  1. Because overriding variables would fundamentally break code in the superclass. For example, if an override changes the variable's type, that is likely to change the behavior of methods declared in the parent class that used the original variable. At worst, it renders them uncompilable.

    For example:

       public class Sup {
           private int foo;
           public int getFoo() {
               return foo;
           }
       }
    
       public class Sub extends Sup {
           private int[] foo;
           ...
       }
    

    If Sub.foo overrides (i.e. replaces) Sup.foo, how can getFoo() work? In the subclass context, it would be trying to return a value of a field of the wrong type!

  2. If fields that were overridden were not private, it would be even worse. That would break the Liskov Substitutability Principle (LSP) in a pretty fundamental way. That removes the basis for polymorphism.

  3. On the flipside, overriding fields would not achieve anything that cannot be done better in other ways. For example, a good design declares all instance variables as private and provides getters/setters for them as required. The getters/setters can be overridden, and the parent class can "protect" itself against undesirable overrides by using the private fields directly, or declaring the getters/setters final.


References:

7
  • Because instance variables CANNOT be overridden in Java, but why? why is it done in this manner in Java? What's the reason? Commented Jan 30, 2018 at 16:45
  • 1
    IMO the point 1. doesn't hold as we know that Java only allows same or covariant return types for overridden methods so same can be assumed for overridden instance variables(if it was implemented). So in this case the getFoo method will work perfectly fine as it can return a variable foo of type Say Number or any subclass of Number like Integer.
    – YK S
    Commented Jan 3, 2019 at 18:54
  • 1
    Also if the above point holds then the LSP won't break as getFoo can return Integer and all subtypes of Integer.
    – YK S
    Commented Jan 3, 2019 at 19:04
  • You are basically saying "if we change the example we can make it work". Unfortunately, the ideas that you proposed won't work with int versus int[]. That's why I chose those types in my example. They are not related by subtyping, so covariance does not help. And this does break LSP.
    – Stephen C
    Commented Jan 3, 2019 at 22:46
  • If they were (hypothetically) to support field overriding, it would need to work for all field types, and all use cases. Otherwise it would be a complicated mess. (Don't imagine that the Java language designers never thought about this ....)
    – Stephen C
    Commented Jan 3, 2019 at 22:50
4

You may refer following section / examples in Java language specification that explains about the topic.

  1. Example 8.3.1.1-3. Hiding of Instance Variables
  2. Section 8.4.8. Inheritance, Overriding, and Hiding and related examples

Rest of my post is an additional information for those who are interested in scratching the surface of jvm internals on this subject. We can start by examining the byte codes generated for class A using javap. Following disassembles the byte codes into a human readable text based instructions (mnemonics).

javap -c A.class 

Without getting lost in many details of the entire dis-assembly, we can focus on the lines corresponding to b.print and b.a

9: invokevirtual #4                  // Method B.print:()V
...
...
16: getfield      #6                  // Field B.a:I

We can immediately infer that the op codes used for accessing the method and a variable are different. If you are from a C++ school, you could sense that all method calls are virtual by default in java.

Now let us write another class A1 identical to A, but just has a casting for accessing variable 'a' in C.

public class A1 {
  public static void main(String[] args) {
    B b=new C();
    b.print(); //casting is irrelevant here because methods are anyway bound at runtime     System.out.println(((C)b).a);// the casting allows us to access of value of a in C
  }
}

Compile the file and disassemble the class.

javap -c A1.class

You would notice that dis-assembly now points to C.a instead of B.a

19: getfield #6 // Field C.a:I

if you want to dig deep into this, here goes additional information:
- invokevirtual corresponds to opcode 0xb6
- getfield corresponds to opcode 0xb4

You can find a JVM specification that explains comprehensively about these opcodes at - http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html
Check out in amazon.com for "Java Virtual Machine" books that could make life little more easier for decoding the specification.

4
  • 3
    This is all completely unnecessary, and a very poor way to approach the problem. You only have to refer to the Java Language Specification where these semantics are defined.
    – user207421
    Commented Aug 12, 2013 at 0:49
  • 2
    You are right from the aspect that the JVM internal may not be needed for a simple answer. But I think it is useful in some cases to look under the hood especially when we have a convenient tool such as javap. I have slightly altered the post. Let me know if you have any additional feedback.
    – Shree
    Commented Aug 12, 2013 at 2:16
  • Since you asked for more feedback ... this is about as "useful" as a driving instructor telling a learner driver to "look under the hood" to find out how to start a car ... IMO.
    – Stephen C
    Commented Aug 12, 2013 at 7:13
  • 4
    Opinion well taken and added reference to language spec. IMO - information provided is not totally irrelevant, may be useful for people from non-OO/different language background such as "C" who are curious enough to look under the hood - Thanks.
    – Shree
    Commented Aug 12, 2013 at 12:24
3

I have modified your code for easy Explanation ,instead of variable 'a' ,lets say the Class C contains variable 'c'. Its for the same reason why class C cannot access the instance variable of Class c itself without Typecasting. Example Given below

class B
{
     int a=10;
     public void print()
     {
         System.out.println("inside B super class");
     }

}
 class C extends B
 {
     int x=20;
     public void print()
     {
         System.out.println("inside C sub class");
     }


 }
public class A  {
    public static void main(String[] args) {
        B b=new C();

        System.out.println(b.x);//will throw compile error unless b is type casted to Class C

    }

}

So,in java,the compiler goes by the reference,not by the instance. To get over this compiler uses Runtime polymorphism,but it is for the methods,not the instance variables. So variables cannot be accessed without type-casting and the methods unless,overridden(Runtime polymoprhism),cannot be accessed without type-casting.

So,in our case.it is obvious for refrence of Superclass carrying an instance of subclass,to view in the superclass.

3

Because variables in Java do not follow polymorphism and overriding is only applicable to methods but not to variables.

In Java, when the child and parent class both have a variable with the same name, Child class's variable hides the parent class's variable, even if their types are different. And this concept is known as Variable Hiding.

In the case of method overriding, overriding methods completely replaces the inherited methods but in variable hiding child class hides the inherited variables instead of replacing which basically means is that the object of Child class contains both variables but Child's variable hides Parent's variable. so when we try to access the variable within Child class, it will be accessed from the child class.

If we are trying to access the variable outside of Parent and Child class, then the instance variable is chosen from the reference type.

Why Instance Variable Is Chosen from Reference Type Instead Of Instance

As explained in How Does JVM Handle Method Overloading and Overriding Internally, at compile time overriding method calls are treated from the reference class only but all overridden methods get replaced by the overriding method at the runtime using a vtable and this phenomenon is called runtime polymorphism.

Similarly, at compile time variable access is also treated from the reference type but as we discussed variables do not follow overriding or runtime polymorphism, so they are not replaced by child class variables at the runtime and still refer to the reference type.

Why Variables do not Follow Overriding Or Why They Follow Hiding

Because variable overriding might break methods inherited from the parent if we change the variable's type in the child class.

We know every child class inherits variables and methods (state and behavior) from its parent class. Imagine if Java allows variable overriding and we change the type of a variable from int to Object in the child class. It will break any method which is using that variable and because the child has inherited those methods from the parent, the compiler will give errors in the child class.

And as mentioned, if Java allows variable overriding then Child's variable cannot substitute Parent's variable and this would break the Liskov Substitutability Principle (LSP).

You can read more on my articles What is Variable Shadowing and Hiding in Java, Why Instance Variable Of Super Class Is Not Overridden In Sub Class

2
1

Like others have mentioned, you cannot override a super class's instance variables, but you can use constructors to assign the proper values for your objects. For example, you can use constructors to make the value of 'a' equal to '20' in class C.

This is your original code that is augmented using constructors to set the value for 'a' equal to '20' in class C.

Long story short, we are using the arguments of an object instance and of a constructors to pass up a value to the superclass.

 public class B {
        private int a; //initialize int a
        public int getA() { //create a getter for a
            return a;
        }
    public B(int size) { //constructor that takes an int
            a = size; //sets a to the value in the parameters
        }
        public void print() {
            System.out.println("inside B superclass");
        }
    }

public class C extends B{
    public C(int a) { //C constructor takes an int
        super(a); //it send the name up to its superclass (B)
    }
    public void print() {
        System.out.println("inside C subclass");
    }
}

public class A {
    public static void main(String[] args) {
        B b = new C(20); //Creates a new object 'b' of type C
        b.print(); // prints: inside C subclass
        System.out.println(b.getA()); // prints the value '20'
    }
}
0

Here is my perspective at a design/conceptual level on why instance variables are not overridden. To keep it simple, if we consider abstract classes, they define abstract methods and expect them to be overridden. There has been never been anything like abstract variables. If there was, then we could expect language to support it by overriding. So, when an abstract class is being designed, then the designer defines some common concrete state and common behavior (including abstract methods) for subtypes. Almost always if state is to be inherited (protected access), then it would be simply inherited and I believe in very few cases some of it could be re-defined, but very rarely re-declared. So, state is naturally being expected to be simply inherited while behavior is being expected to be inherited and overridden.

-1

As instance variables don't get overridden in java there is no run time polymorphism associated with them and hence at compile time only it is decided by reference.

In your code

B b = new C();
b.print();

As b is of type Class B which is Parent to C and hence as there is no 
run time polymorphism it is decided at compile time to call instance 
variable of Class B.
1
  • 1
    I think this is a misleading example.. b.print() is a method, and this would in fact call the overriding print method if it was declared in the C class.
    – camel-man
    Commented Dec 7, 2018 at 19:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.