Search code examples
javainheritancesuperclass

Access overwritten fields of super class in Java?


I have named one of my fields in my subclass the same as in my superclass. I have basically overwritten the fields in my parent class.

How can I distinguish the field from the base class from the field with the same name in the extended class?


Solution

  • The keyword super is most of the times used in conjunction to accessing superclass methods, most of the times a constructor from the parent class .

    The keyword this is most of the times used to distinguish fields of the class from method parameters or local variables with the same name.

    However, you can also use super to access fields of the superclass or this to call methods (which is redundant since all calls are virtual methods calls), or another constructor from the same class.

    Here is an example of the usage for accessing fields.

    public class Base {
    
        public int a = 1;
        protected int b = 2;
        private int c = 3;
    
        public Base(){
    
        }
    }
    
    public class Extended extends Base{
    
        public int a = 4;
        protected int b = 5;
        private int c = 6;
    
        public Extended(){
    
        }
    
        public void print(){
            //Fields from the superclass
            System.out.println(super.a);
            System.out.println(super.b);
            System.out.println(super.c); // not possible
    
            //Fields from the subclass
            System.out.println(this.a);
            System.out.println(this.b);
            System.out.println(this.c);
        }
    }
    
    public static void main(String[] args) {
            Extended ext = new Extended();
            ext.print();
        }
    

    You can always rename the fields in your subclasses not to conflict, but if you want to distinguish a method parameter or local variable from the superclass field, use super as you would use this