Search code examples
javaabstract-class

Java Abstract classes good practices


I am just now learning about Abstract classes in Java and I was wondering.
Would having package private fields be considered bad practices?
For example:

abstract class Parent {
    String testField;

    public void method() {
        System.out.println(testField);
    }
}

Then on the children class I would do

public final class Children extends Parent {

    @Override
    public void method() {
        logger.log(testField);
    }

}

In this example would it be bad practice?
Or should I make them private and instead use getters and setters for them like normally?


Solution

  • It depends on what you want to do. However, in many cases encapsulation or information hiding can be a useful principle. In your case, this would mean making the member variable protected or private and exposing it only through getters/setters or not at all. This yield some advantages:

    • You can change the implementation of your class (e.g. changing the type of testField) without breaking the code of other programmers
    • The code is more clear to other programmers as they only need to consider the public methods
    • It makes the code easier to test
    • It discourages feature envy and tight coupling