0

I've been writing Java for some years, but I still do not understand why this simple example class below actually passes compilation. In this situation, I would make a getter method for myInt, and use that method to fetch the myInt from o in my compareTo method, as myInt is declared private. Could someone please tell me why on earth this is a legal way to access o's myInt?

public class B implements Comparable<B> {

    private int myInt = 0;

    public int compareTo(B o) {
        return myInt-o.myInt;
    }

}

Thanks in advance!

Henrik Hillestad Løvold
  • 1,213
  • 4
  • 20
  • 46
  • 3
    `private` has `class` scope. You are still in the same class. – PM 77-1 Mar 01 '15 at 20:14
  • 1
    You are already in the same class with B. Private members are accessible from the same class. Check: http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html Access Modifiers private modifier—the field is accessible only within its own class. – Onur Aktaş Mar 01 '15 at 20:15
  • 1
    " a class always has access to its own members" - http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – doog abides Mar 01 '15 at 20:16
  • Thanks guys, I assumed that was the reason. Post it as an answer and I'll be glad to accept. – Henrik Hillestad Løvold Mar 01 '15 at 20:16

2 Answers2

3

According to Oracle's Java Tutorial

Access level modifiers determine whether other classes can use a particular field or invoke a particular method.

Access level has been designed at the class level, and it does not depends on instances.

davide
  • 1,918
  • 2
  • 20
  • 30
1

According to Java API:

The private modifier specifies that the member can only be accessed in its own class.

As a class always has access to its own members. Your codes are allowed and it will not give your compilation error.

Take a look at this (Changing B to C):

class B implements Comparable<B> {

    private int myInt = 0;

    public int compareTo(C o) {
        return myInt-o.myInt;
    }

}

class C
{
    private int myInt = 0;
}

If you try changing B to C (another class). It will give you compilation error.

user3437460
  • 17,253
  • 15
  • 58
  • 106