baggy696
baggy696

Reputation: 77

Checkstyle error for protected variable in abstract classes

I'm kind of new to java and I'm facing an issue with protected variable in an abstract class. I've added the implementation below:

Abstract class:

public abstract class blah1 implements blah {
   protected variable1
   //// stuff///
}

sub class:

public class blah2 extends blah1 {
   ///uses variable1///
}

Checkstyle says I should convert the variable to private and then use get/set methods. But how do I accomplish this within an abstract-class/sub-class situation?

Upvotes: 0

Views: 538

Answers (1)

AddeusExMachina
AddeusExMachina

Reputation: 612

Make variable private in parent class, then add getter and setter

public abstract class blah1 {
  private int variable;

  public int getVariable() {
    return variable;
  }

  public void setVariable(int variable) {
    this.variable = variable;
  }
  //// stuff///
}

How to use it in the child class. Note the super keyword

public class blah2 extends blah1 {

  void useVariable() {
    super.getVariable(); // get variable
    super.setVariable(1); // set variable
  }

}

EDIT
As stated by @Pshemo it's legit removing the super keyword (and you should do it if you're planning to override the getter and setter in order to use the overriden version) obtaining:

void useVariable() {
    getVariable(); // get variable
    setVariable(1); // set variable
}

Anyway the version using super lets you understand how you can call the original version of those methods

Upvotes: 1

Related Questions