Programming

변경 가능한 객체와 변경 불가능한 객체의 차이점

procodes 2020. 8. 15. 14:19
반응형

변경 가능한 객체와 변경 불가능한 객체의 차이점


이 질문에 이미 답변이 있습니다.

누구든지 예를 들어 Mutable 객체와 Immutable 객체의 차이점을 알려주십시오.


변경 가능한 개체에는 변경할 수있는 필드가 있고, 변경 불가능한 개체에는 개체가 생성 된 후 변경할 수있는 필드가 없습니다.매우 단순한 불변 객체는 필드가없는 객체입니다. (예를 들어 간단한 비교기 구현).

class Mutable{
  private int value;

  public Mutable(int value) {
     this.value = value;
  }

  //getter and setter for value
}

class Immutable {
  private final int value;

  public Immutable(int value) {
     this.value = value;
  }

  //only getter
}

변경 가능한 개체는 생성 후 필드를 변경할 수 있습니다. 불변 객체는 할 수 없습니다.

public class MutableClass {

 private int value;

 public MutableClass(int aValue) {
  value = aValue;
 }

 public void setValue(int aValue) {
  value = aValue;
 }

 public getValue() {
  return value;
 }

}

public class ImmutableClass {

 private final int value;
 // changed the constructor to say Immutable instead of mutable
 public ImmutableClass (final int aValue) {
  //The value is set. Now, and forever.
  value = aValue;
 }

 public final getValue() {
  return value;
 }

}

불변 객체는 단순히 상태 (객체의 데이터)가 생성 후에 변경 될 수없는 객체입니다. JDK의 변경 불가능한 객체의 예로는 String 및 Integer가 있습니다.예 :( 포인트는 변경 가능하고 문자열은 변경 불가능합니다)

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

출력은 다음과 같습니다.

java.awt.Point[0.0, 0.0]
java.awt.Point[1.0, 0.0]
old String
old String

Immutable Object's state cannot be altered.

for example String.

String str= "abc";//a object of string is created
str  = str + "def";// a new object of string is created and assigned to str

They are not different from the point of view of JVM. Immutable objects don't have methods that can change the instance variables. And the instance variables are private; therefore you can't change it after you create it. A famous example would be String. You don't have methods like setString, or setCharAt. And s1 = s1 + "w" will create a new string, with the original one abandoned. That's my understanding.

참고URL : https://stackoverflow.com/questions/4658453/difference-between-mutable-objects-and-immutable-objects

반응형