简体   繁体   中英

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

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.

好的,我在弄乱自己的代码,发现问题是我需要超类C的受保护的默认构造函数。它现在可以工作...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM