0

A question about inheritance in java...

class Base {
    private int val = 10;
}

class Derive extends Base{
    public void setVal(int value) {
        super.val = value;
    }
}

Since we can change the private field in super class using super keyword in the subclass, why should we use protected to declare fields in super class?

wattostudios
  • 8,666
  • 13
  • 43
  • 57
alaska
  • 151
  • 2
  • 8
  • 1
    first of all, as the answer states this won't compile, you can't access private fields, second even if you could, please use setters/getters even internally. – Samy Vilar Jun 16 '12 at 07:54

3 Answers3

4

You can't do that. The code you've given doesn't compile, unless Derive is declared as a nested class within Base (which is a pretty rare case).

You should be getting an error like this:

error: val has private access in Base
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • yes, thanks. I used nested static class for test. It supposed that I should never do this to test accessibility again. – alaska Jun 17 '12 at 18:21
0

super is an reference variable which is used to call parents constructor.

saurabh kumar
  • 155
  • 5
  • 26
0

Check your code you can never access private out side the class even if you have inherited that class.

saurabh kumar
  • 155
  • 5
  • 26