Billies Wesley
Billies Wesley

Reputation: 457

What maintenance problems are associated with protected variables in java

So my lecturer said something along the lines of:

Declaring variables as protected exposes them to all subclasses, can cause a maintenance problems, best to declare variables as private (even in inheritance relationships) and write getter and setter methods to provide access to variables.

But he didn't explain what the maintenance problems were. What issues are there if subclasses can access variables.

Im pretty new to java, so a simplistic explanation would be more helpful

Upvotes: 2

Views: 313

Answers (3)

Andy Turner
Andy Turner

Reputation: 140534

Check out Effective Java 2nd Ed Item 14: "In public classes, use accessor methods, not public fields".

This is talking about a slightly different case (public fields, rather than protected fields), but it gives a good description of why exposing fields outside the class is generally worth avoiding. In a sense, protected fields are like public fields, in that they are accessible outside the class, by any subclass.

The particularly relevant quote is:

You can’t change the representation without changing the API, you can’t enforce invariants, and you can’t take auxiliary action when a field is accessed.

In other words, once you've exposed the field to subclasses, you're then committed to preserving that field as a field forever after, unless you are able to update all subclasses (which you almost certainly can't, unless you're working in a closed environment).

Upvotes: 1

Jack
Jack

Reputation: 3059

With getter and setter methods, you can control what happens when the member is changed or accessed. If for example you get the maintenance task to perform some checks before the member is changed, you can easily do this, if you have designed your class with a setter method. If the member is however just protected, you would have to find where it is changed within all of the subclasses. Your maintenance task would include refactoring the sublasses instead of just doing changes to the setter method.

Upvotes: 1

Eran
Eran

Reputation: 394126

Suppose that you write a class with a protected instance variable :

public class A {
    protected int c;
}

Now, someone else can extend your class and use the c variable directly :

public class B extends A {
    public void someMethod () {
        System.out.println(c + 5);
    }
}

Now B depends on the c member of your class A. If tomorrow you decide to remove that variable, or rename it, or change its type, B won't pass compilation.

When you make c private and supply a getter and a setter to access it, you have the liberty of changing c without breaking classes that extend your class.

Upvotes: 5

Related Questions