Snippet #1:
public abstract class SuperClass {
protected int i;
}
public class SubClass extends SuperClass {
public void method() {
i = doAnythingWithI(i); // for example
}
}
Snippet #2:
public abstract class SuperClass {
private int i;
protected int getI() {
return i;
}
protected int setI(int i) {
this.i = i;
}
}
public class SubClass extends SuperClass {
public void method() {
setI(doAnythingWithI(getI())); // for example
}
}
Any reason why using one snippet instead of the other one? What is the most common way to process?
One of the more common uses of an abstract class is to have abstract methods that are not implemented in abstract class, but implemented in subclasses in java program. This is obviously not your use case. However, an abstract class can also be used as a way of preventing someone from instantiating a class that is supposed to be extended first. I am assuming this is your desire.
Furthermore, I assume the trivial nature of the example is just for illustration. Having two classes to "manage" a single primitive 'int' would probably be suspect otherwise!
Given this and the two choices Snippet #2 is closer to being correct. The reason for this being the desire of a "type" to encapsulate state, data, and behavior. Snippet #1 violates this and would usually be discouraged.
The method "doAnythingWithI" begs discussion though. It is not really declared in your examples. If it operates solely upon "i" and is not subject to alteration by a concrete class, then it also belongs in the abstract base class.
If it can vary with multiple implementations that extend the SuperClass, then it should probably be defined as an abstract method in the SuperClass and implemented by the sub-classes.