Mutable Objects: When you have a reference to an instance of an object, the contents of that instance can be altered Immutable Objects: When you have a reference to an instance of an object, the contents of that instance cannot be altered Immutability and Instances To demonstrate this behaviour, we'll use java.lang.String as the immutable class and java.awt.Point as the mutable class. Point myPoint = new Point( 0, 0 ); System.out.println( myPoint ); myPoint.setLocation( 1.0, 0.0 ); System.out.println( myPoint ); String myString = new String( "old String" ); System.out.println( myString ); myString.replaceAll( "old", "new" ); System.out.println( myString ); In case you can't see what the output is, here it is: java.awt.Point[0.0, 0.0] java.awt.Point[1.0, 0.0] old String old String We are only looking at a single instance of each object, but we can see that the contents of myPoint has changed, but the contents o
Comments
Post a Comment