1

Strangely, instance variable brand is private scope, yet accessible the "public" way inside of method compareTo.

public class Car implements Comparable<Car> {
    private String brand;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int compareTo(Car o) {
        return this.brand.compareTo(o.brand);
    }
}
Oh Chin Boon
  • 23,028
  • 51
  • 143
  • 215

3 Answers3

4

Class variable brand is private to other classes not the class Car itself.

for instance if you try

class Foo
{
     Foo()
     {
          Car car = new Car();
          string brand = car.brand; // <-- will not compile; 
                                    // should use car.getBrand()
     }
}
Bala R
  • 107,317
  • 23
  • 199
  • 210
2

You can access the brand member of the instance O because you are in another instance of the same type

iamkrillin
  • 6,798
  • 1
  • 24
  • 51
1

Private specifies that the variable can only be accessed by members of the class. There is nothing wrong with the scenario above.

Sagar V
  • 1,916
  • 15
  • 23