Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

가변 객체와 불변 객체의 차이점

<시간/>

Java에서 불변 객체의 상태는 생성된 후에 수정할 수 없지만 다른 객체를 확실히 참조합니다. 다중 스레드는 객체의 상태를 변경할 수 없으므로 불변 객체는 스레드로부터 안전하기 때문에 다중 스레드 환경에서 매우 유용합니다. 불변 객체는 시간적 커플링을 피하고 항상 원자성이 실패하는 데 매우 유용합니다.

반면, Mutable 객체에는 변경할 수 있는 필드가 있고, immutable 객체에는 객체가 생성된 후 변경할 수 있는 필드가 없습니다.

Sr. 아니요. 변경 가능한 개체 불변 개체
1
기본
변경 가능한 객체가 생성된 후 상태를 수정할 수 있습니다.
생성된 객체의 상태를 수정할 수 없습니다.
2
스레드 안전
변경 가능한 객체는 스레드로부터 안전하지 않습니다.
불변 객체는 스레드로부터 안전합니다.
3
최종
변경 가능한 클래스는 최종적이지 않습니다.
불변 객체를 생성하려면 클래스를 final로 만드세요.
4
예시
기본적으로 모든 클래스와 해당 객체는 본질적으로 변경 가능합니다.
문자열과 모든 래퍼 클래스는 불변 클래스의 예입니다.

불변 클래스의 예

public final class ImmutableClass {
   private String laptop;
   public String getLaptop() {
      return laptop;
   }
   public ImmutableClass(String laptop) {
      super();
      this.laptop = laptop;
   }
}
public class Main {
   public static void main(String args[]) {
      ImmutableClass immutableClass = new ImmutableClass("Dell");
      System.out.println(immutableClass.getLaptop());
   }
}

변경 가능한 클래스의 예

public class MuttableClass {
   private String laptop;
   public String getLaptop() {
      return laptop;
   }
   public void setLaptop(String laptop) {
      this.laptop = laptop;
   }
   public MuttableClass(String laptop) {
      super();
      this.laptop = laptop;
   }
}
public class Main {
   public static void main(String args[]) {
      MuttableClass muttableClass = new MuttableClass("Dell");
      System.out.println(muttableClass.getLaptop());
      muttableClass.setLaptop("IBM");
      System.out.println(muttableClass.getLaptop());
   }
}