sbose
sbose

Reputation: 1811

In Java , Can't access protected members of super-class from sub-class

class Super {
   protected int a;
   protected Super(int a) { this.a = a; }
}

class Sub extends Super {
    public Sub(int a) { super(a); }
    public Sub() { this.a = 5; }
}




  public Sub() { this.a = 5; }  

this.a=5 doesn't work. Why is this so? Protected and public members should be inherited.

Upvotes: 0

Views: 2112

Answers (3)

polve
polve

Reputation: 3138

What does not work? Works for me...

What you do not have is a default constructor - in public Sub() {this.a = 5; } the parent default constructor is called, which you have not provided. If I compiler your code I get:

cannot find symbol constructor Super()

So you either have to have a default constructor or do: public Sub() { super(5); }

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

Your parameterless constructor in Sub is attempting to implicitly invoke a parameterless constructor in Super which doesn't exist, which is (I assume) why you're getting a compile error.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

The problem isn't that you access the variable, but that you don't call the base constructor:

class Super {
   protected int a;
   protected Super(int a) { this.a = a; }
}

class Sub extends Super {
    public Sub(int a) { super(a); }
    public Sub() { 
       super(0);  // <-- call base constructor
       this.a = 5; 
    }
}

This happens because you didn't define a default constructor for Super, so derived classes don't know which constructor to call if you're not specifying one.

Upvotes: 9

Related Questions