0

The answer for the below code is 2. Why is 5 not getting printed even though the class instantiated is 5? I do see 5 when I override the getter and setter.

  public class Base {

        private int count = 2;

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

    }


    public class Subclass extends Base {

        private int count = 5;

    }


    public class PolyMain {

        public static void main(String[] args){
            Base base = new Subclass();
            System.out.println(base.getCount());

        }

    }
Punter Vicky
  • 15,954
  • 56
  • 188
  • 315
  • 1
    `getCount()` refers to `Base.count`. Defining a field in the subclass with the same name doesn't override that field, it just defines another field. – Andy Turner Oct 14 '16 at 09:13
  • Thanks Andy , so effectively there are 2 variables with same name and in order to access the parent , I need to use super.count? – Punter Vicky Oct 14 '16 at 09:14
  • There are two variables; but you can't access `super.count` because it's private, and `Subclass` is not nested inside `Base`. – Andy Turner Oct 14 '16 at 09:15
  • Thanks , so I should be use super.getCount() in case I override the getCount method in subclass and want to access the one in parent. Thanks @AndyTurner. This helps! – Punter Vicky Oct 14 '16 at 09:17

0 Answers0