1

Why am I able to directly access p's private number attribute within Striker's implementation of the hasSameNumber method? Seems as though using the getter should be the only (if not, best-practice) way to access it. What am I missing?

public class Football {

    public static abstract class FootballPlayer {
        private final int number;

        FootballPlayer(int num) {
            number = num;
        }

        int getNumber() {
            return number;
        }

        abstract boolean hasSameNumber(FootballPlayer p );
    }

    public static class Striker extends FootballPlayer {
        Striker(int num) {
            super(num);
        }
        boolean hasSameNumber(FootballPlayer p ) {
            return this.getNumber() == p.number;
        }
    }

}

Edit:

The accepted answer shows why this is permissible - thanks! What would be the preferred/best-practice way to access number though - by getter or direct?

  • 1
    The equivalent C++ code would not be valid. You can add a language tag like Java to get an answer for a specific language. – aschepler Feb 12 '22 at 14:25
  • The edit is an opinion-based question and therefore not allowed on Stack Overflow. – pppery Feb 13 '22 at 17:44

1 Answers1

1

Java - the access to number occurs within the body of Football, thus is allowed.

JLS 6.6.1

I admit I was surprised by this specific example.

passer-by
  • 1,103
  • 2
  • 4
  • ah great, thanks – WobbleMeister Feb 12 '22 at 16:05
  • is there a clear best practice to apply here? Use the getter or access the attribute directly? – WobbleMeister Feb 12 '22 at 16:08
  • I'd tend to saying *number* should be a protected field (to show intent, even if the language allows access to privates) and the subclasses should just read it directly. In this case, simple-minded getters have no benefit. – passer-by Feb 12 '22 at 16:42
  • Yes, I would agree. I think if I hypothetically _had_ to choose between directly accessing the private variable or a getter, I'd go for the getter, but yes, protected signals far clearer intent – WobbleMeister Feb 12 '22 at 17:45