简体   繁体   中英

Are the objects in the following class immutable?

public class Point {
       private double x;
       private double y;
       Point (double x, double y) 
       { this.x = x; this.y = y; }
       double getX() { return x; }
       double getY() { return y; }       }

Are the objects in the above class immutable? Explain. I am getting confused because There r no setters so nothing can modify the objects BUT there is no final variable or final class which it should contain.

If the class gets extended, it could add extra fields that are not immutable, or the methods could be overridden to return a different value each time. Doesnt this make the class not immutable?

If the class gets extended, ... the methods could be overridden to return a different value each time. Doesn't this make the class not immutable?

Your question is subtle. If some class MutPoint extends Point and overrides the getX() and getY() methods to return non-constant values, that doesn't change the Point class itself. Instances of Point sill will be effectively immutable, but a caller would be allowed to pass MutPoint objects to your methods that expect Point arguments. What happens then? Depends on how you write your code. It could be that your code would behave badly if the caller gave you a Point-like object, and then subsequently changed its "value".

If your code that uses Point objects requires them to never change, then you might want to declare the whole class final

public final class Point { ... }

That way, your client will not be allowed to override the class, and will not be allowed to call your methods with anything other than an actual Point instance.

Yes, they are immutable. You can read about it here http://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html

是的,因为您无法访问数据成员,并且您没有更改数据成员的方法

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM