markzzz
markzzz

Reputation: 47945

Java - Why protected doesnt work on this function

package portale.interfaccia;
public class PageIndex extends FlowPanel {
    protected Integer prova;

    private PageCenter center;
    public PageIndex() {
        this.center=new PageCenter();
        this.add(center);    
    }
}

package portale.interfaccia;
public class PageCenter extends FlowPanel {
    public PageCenter() {
        super.prova=2;
    }
}

why, if prova is protected, i can't access to it by using super? Cheers

Upvotes: 1

Views: 127

Answers (3)

Tom
Tom

Reputation: 45114

PageCenter extends from FlowPanel, not from PageIndex. It looks like FlowPanel has no attribute named prova

If you want PageCenter to access a protected attribute from PageIndex using the super keyword, then you should extend from PageIndex.

public class PageCenter extends PageIndex{

   public PageCenter(){
      prova = 2;
   }
}

If you want both classes to extend from FlowPanel, try refactoring your code so that PageIndex and PageCenter know some utility class.

public class ProvaUtility{

    private Integer prova;

    public Integer getProva(){}

    public void setProva(Integer p){}
}

Then you could use it like this:

public class PageIndex extends FlowPanel{

    private ProvaUtility utility;

    private PageCenter center;

    public PageIndex(ProvaUtility pu){

        this.utility = pu;
        this.center = new PageCenter(pu);
        this.add(this.center);
    } 

    public Integer getProva(){
         return this.utility.getProva();
     }
}

 public class PageCenter extends FlowPanel{

    private ProvaUtility utility;

    public PageCenter(ProvaUtility u){
       this.utility = u;
       this.utility.setProva(2);
    }
 }

If passing this reference around doesn't make it for you, try using a Singleton

class ProvaSingleton{

   private static ProvaSingleton instance = null;

   private Integer prova;

   private ProvaSingleton(){
      prova = 2;
   }

   public static ProvaSingleton getInstance(){

      if (instance == null){
          instance = new ProvaSingleton();
      }
      return instance;
   }

   public Integer getProva(){ return this.prova;}

   public void setProva(Integer p){this.prova = p;}
}

Then call it by:

ProvaInstance.getInstance().getProva()

Upvotes: 3

Knubo
Knubo

Reputation: 8443

You must make PageCenter extend PageIndex.

Upvotes: 0

Alan Geleynse
Alan Geleynse

Reputation: 25139

super in your PageCenter class is referring to FlowPanel because that is what it is extending.

PageCenter has no way of knowing that it is a member of PageIndex without a reference to that object.

I believe you are confusing inheritance and instance variables.

protected will allow access by the current class and any class that inherits from it. It does not allow other classes in the same package to access it.

Upvotes: 1

Related Questions