Immutable

 Immutable class - is class we can not change.

package Main;

public class Car {
public String name;
}
package Main;

public class Test {
private String name = null;
private Car c = null;

public Test(String name, Car c){
this.name = name;
Car c1 = new Car();
c1.name = c.name;
this.c = c1;
}

public String getName(){
return name;
}

public Car getC(){
Car cc = new Car();
cc.name = c.name;
return cc;
}
}
package Main;

public class Main {

public static void main(String[] args) {
Car c = new Car();
c.name = "Parvin";
Test t = new Test("test", c);
c.name = "alma";
System.out.println(t.getC().name);
System.out.println(c.name);
System.out.println("------------------");
t.getC().name = "armud";
System.out.println(t.getC().name);
System.out.println(c.name);
}
}
Outcome:
Parvin
alma
----------------
Parvin
alma
*But how?
    In the constructor and in method getC() we can easily detect that everytime we 
create new Car object. After we set to the object of this new Car object the value
we already have and then return it. So our old value remains untouched.
    It is like someone aproaches me and requires a document, instead of giving the 
real one I present him a copy of it.
Clear?

Комментарии

Популярные сообщения из этого блога

IoC:ApplicationContext, BeanFactory. Bean

Lesson1: JDK, JVM, JRE

Lesson_2: Operations in Java