Mutable and Immutable classes
Let's see this example:
package com.main;
public class Mercedes {
private int speed;
public Mercedes() {
}
public Mercedes(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
package com.main;
public class BMW {
public Integer speed;
private String color;
private Mercedes mercedes;
public BMW() {
}
public BMW(Integer speed) {
this.speed = speed;
}
public BMW(Mercedes mercedes) {
this.mercedes = mercedes;
}
public Integer getSpeed() {
System.out.println("BMW class");
return speed;
}
public String getColor() {
return color;
}
public Mercedes getMercedes() {
Mercedes m = new Mercedes();
m.setSpeed(mercedes.getSpeed());
return m;
}
}package com.main;
public class FakeBMW extends BMW {
private Integer speed;
public String name = "something";
public FakeBMW(Integer speed) {
this.speed = speed;
}
@Override
public Integer getSpeed() {
System.out.println("FakeBMW class");
return speed;
}
public void setSpeed(Integer speed) {
this.speed = speed;
}
}package com.main;
public class Main {
public static void main(String[] args) {
BMW bmw = new FakeBMW(100);
System.out.println(bmw.getSpeed());
FakeBMW fakeBMW = (FakeBMW) bmw;
String s = ((FakeBMW) bmw).name;
fakeBMW.setSpeed(200);
foo(bmw);
}
public static void foo(BMW bmw){
System.out.println(bmw.getSpeed());
}
}Outcome would be:
FakeBMW class
100
FakeBMW class
200
Explanation:
First of all if we want to create immutable classes we are obliged to not write set methods
inside class and also ohter class object (here Mercedes class object inside BMW) must be
immutable as well.
When I was preparing that, I came accross with one novelty. I have not faced with it before
and started to dig deep. So I created FakeBMW object bmw (for example reference 111). By the
way this is upcasting. Then I tried to print bmw.getSpeed(); I initially thought that the
outcome would be null. In reality it happens like this: 1-> BMW has getSpeed() method JVM
calls this method but body of this method inside of FakeBMW 2-> JVM runs body of getSpeed()
which is inside FakeBMW 3-> then it gets variable inside itself (however I thought I would get
variable of the BMW class).
Комментарии
Отправить комментарий