Overriding a super class's instance variables

后端 未结 9 1914
暗喜
暗喜 2020-11-30 07:47

Why are we not able to override an instance variable of a super class in a subclass?

相关标签:
9条回答
  • 2020-11-30 08:12

    you can override a method,that is all right but what do you mean by overriding a variable? if you want to use a variable at any other place rather than super class u can use super. as in super(variable names); why do you want to override a variable? i mean is there any need?

    0 讨论(0)
  • 2020-11-30 08:14

    If you have the need to override an instance variable, you are almost certainly inheriting from the worng class.

    In some languages you can hide the instance variable by supplying a new one:

    class A has variable V1 of type X;
    
    class B inherits from A, but reintroduces V1 of type Y.
    

    The methods of class A can still access the original V1. The methods of class B can access the new V1. And if they want to access the original, they can cast themself to class A (As you see dirty programming provokes more dirty progrtamming).

    The best solution is to find another name for the variable.

    0 讨论(0)
  • 2020-11-30 08:17

    Do you mean with overriding you want to change the datatype for example?

    What do you do with this expression

    public class A {
       protected int mIndex;
    
       public void counter(){
          mIndex++;
       }
    
    }
    
    public class B extends A {
       protected String mIndex; // Or what you mean with overloading
    }
    

    How do you want to change the mIndex++ expression without operator overloading or something like this.

    0 讨论(0)
提交回复
热议问题