Can I make a protected member public in Java? I want to access it from a subclass
I'm new to Java and OOP,
I was using a private subclass (actually a struct) B in a class A, and everything went well until I decided to make a parent class C for subclass B. I want make public some of the protected members of class C.
For example:
public class A {
private class B extends C {
public int product;
public int x;
public int y;
public void add() {
product=x+y;
}
}
B b=new B;
b.x=1;
b.y=2;
b.multiply();
System.out.println(b.product+"="+b.x+"x"+b.y);
public class C {
protected int x;
protected int y;
public int sum;
public C(px,py) {
x=px;
y=py;
}
public void sum() {
sum=x+y;
}
}
And I get
开发者_C百科Implicit super constructor C() is undefined for default constructor. Must define an explicit constructor
Of course, I could remove extends C, and go back to what I had before. Or I could make a getter/setter. But I think it is understandable that an inner struct is acceptable, and it should be able to extend other classes.
The compiler message is reasonably clear - in B you've effectively got:
public B() {
super();
}
and that fails because there's no parameterless constructor in C to call. Either introduce a parameterless constructor, or provide an explicit constructor in B which calls the constructor in C with appropriate arguments.
I'm not sure it's a good idea to have all these non-private fields, mind you - nor is it a good idea for fields in B to hide fields in C. Do you really want an instance of B to have two x
fields and two y
fields? You realise they will be separate fields, don't you?
If you just want to effectively provide public access, you could have:
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
(and the same for y
) and remove the extra fields from B. You can't change the actual accessibility of the fields in C though.
Okay, I was fuddling with my own code and found that the problem is I needed a protected default constructor for superclass C. It works now...
精彩评论