开发者

private instance variable accessible with "public" scope inside compareTo

开发者 https://www.devze.com 2023-03-27 19:02 出处:网络
Strangely, instance variable brand is private scope, yet accessible the \"public\" way inside of method compareTo.

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);
    }
}


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()
     }
}


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消