Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance - instance variables overriding

Tags:

java

Why are Instance variables of a superclass not overidden in Inheritance ?

like image 456
Saurabh Gokhale Avatar asked Mar 17 '10 16:03

Saurabh Gokhale


People also ask

Can we override an instance variable?

Overriding is only applicable to methods but not to variables. In Java, if 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. This concept is known as Variable Hiding.

Is overriding possible in inheritance?

5.4 Overriding Inherited MethodsA derived class has the ability to redefine, or override, an inherited method, replacing the inherited method by one that is specifically designed for the derived class.

Do child classes inherit instance variables?

child class - The class that is doing the inheriting is called the child class. It inherits access to the object instance variables and methods in the parent class.


2 Answers

You can hide a field, but not override it.

Hiding means that a field will have a different value depending from which class it's accessed. The field in the subclass will "hide" the field in the super-class, but both exists.

That's an extremely bad practice to hide field, but works:

public class HideField {

    public static class A
    {   
        String name = "a";

        public void doIt1() { System.out.println( name ); };
        public void doIt2() { System.out.println( name ); };   
    }

    public static class B extends A
    {
        String name = "b";

        public void doIt2() { System.out.println( name ); };
    }

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

        a.doIt1(); // print a
        b.doIt1(); // print a
        a.doIt2(); // print a
        b.doIt2(); // print b <-- B.name hides A.name
    }
}

Depending on whether the method was overriden, the field in A or B is accessed.

Never do that! That's never the solution to your problem and creates very subtle bugs related to inheritance.

like image 73
ewernli Avatar answered Oct 07 '22 21:10

ewernli


Because inheritance is intended to modify behaviour. Behaviour is exposed through methods, and that's why they can be overridden.

Fields are not behaviour but state. You don't need to modify that, nor the private methods employed by the superclass. They are intended to allow the superclass to do it's job.

like image 43
extraneon Avatar answered Oct 07 '22 22:10

extraneon