Overriding a super class's instance variables

后端 未结 9 1913
暗喜
暗喜 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:00

    Because if you changed the implementation of a data member it would quite possibly break the superclass (imagine changing a superclass's data member from a float to a String).

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

    Variables aren't accessed polymorphically. What would you want to do with this that you can't do with a protected variable? (Not that I encourage using non-private mutable variables at all, personally.)

    0 讨论(0)
  • 2020-11-30 08:01
    class Dad{
        public String name = "Dad";
    }
    class Son extends Dad{
        public String name = "Son";
        public String getName(){
            return this.name;
        }
    }
    

    From main() method if you call

    new Son().getName();
    

    will return "Son" This is how you can override the variable of super class.

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

    Because you can only override behavior and not structure. Structure is set in stone once an object has been created and memory has been allocated for it. Of course this is usually true in statically typed languages.

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

    He perhaps meant to try and override the value used to initialize the variable. For example,

    Instead of this (which is illegal)

    public abstract class A {
        String help = "**no help defined -- somebody should change that***";
        // ...
    }
    // ...
    public class B extends A {
        // ILLEGAL
        @Override
        String help = "some fancy help message for B";
        // ...
    }
    

    One should do

    public abstract class A {
        public String getHelp() {
            return "**no help defined -- somebody should change that***";
        }
        // ...
    }
    // ...
    public class B extends A {
        @Override
        public String getHelp() {
            return "some fancy help message for B";
        // ...
    }
    
    0 讨论(0)
  • 2020-11-30 08:07

    we can not overriding structure of instance variables ,but we ovverride their behavior:-

    class A
    {
    int x = 5;
    }
    
    class B extends A
    {
    int x = 7:
    }
    
    class Main
    {
    public static void main(String dh[])
    {
    A obj = new B();
    System.out.println(obj.x);
    }
    }
    

    in this case output is 5.

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