javatechie

Custom Immutable class in java

Sep 27th, 2019
355
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. package com.javatechie.interview.programming;
  2.  
  3. import java.util.Collections;
  4. import java.util.Date;
  5. import java.util.List;
  6.  
  7. final public class MyImmutable {
  8.  
  9.     final private int id;
  10.     final private String name;
  11.     final private Customer customer;
  12.     final private List<String> list;
  13.     final private Date date;
  14.  
  15.     public MyImmutable(int id, String name, Customer customer, List<String> list, Date date) {
  16.         this.id = id;
  17.         this.name = name;
  18.         this.customer = customer;
  19.         this.list = list;
  20.         this.date = date;
  21.     }
  22.  
  23.     public int getId() {
  24.         return id;
  25.     }
  26.  
  27.     public String getName() {
  28.         return name;
  29.     }
  30.  
  31.     public Customer getCustomer() throws CloneNotSupportedException {
  32.         return (Customer) this.customer.clone();
  33.  
  34.     }
  35.  
  36.     public List<String> getList() {
  37.         return Collections.unmodifiableList(this.list);
  38.     }
  39.  
  40.     public Date getDate() {
  41.         return (Date) date.clone();
  42.     }
  43.  
  44.     public static void main(String[] args) {
  45.         MyImmutable myImmutable = new MyImmutable(1, "javatechie", new Customer(), Collections.emptyList(), new Date());
  46.         List<String> myList = myImmutable.list;
  47.         myList.add("abc");
  48.         System.out.println("Expected Exception : " + myList);
  49.  
  50.     }
  51. }
  52.  
  53.  
  54. package com.javatechie.interview.programming;
  55.  
  56. public class Customer implements  Cloneable {
  57.  
  58.     public Object clone() throws CloneNotSupportedException {
  59.         return super.clone();
  60.     }
  61. }
Add Comment
Please, Sign In to add comment