Exercise 4-2 (Aliasing objects)
Chapter_4 Exercise_4-1 Sum | Exercise_4-3 |
Exercise 4-2 TIJ, p. 66
Exercise 4-2: (1) Create a class containing a float and use it to demonstrate aliasing.
Assignment.java TIJ, p. 65
import static java.lang.System.out;
class Tank
{
float level;
}
public class Assignment
{
static void println(Object obj) {out.println(obj);}
public static void main(String[] args)
{
Tank t1 = new Tank();
Tank t2 = new Tank();
// t1.level = 9; // int to float OK, no precision loss
t1.level = 9.0f; // 9.0 is implicitly double (compile error)
t2.level = 47.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = t2.level; // not aliasing the fields
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = 27.0f;
t2.level = 57.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1 = t2; // aliasing objects
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t1.level = 27.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
t2.level = 57.0f;
println("t1.level: " + t1.level + ", t2.level: " + t2.level);
}
}
/*
javac Assignment.java
java Assignment
t1.level: 9.0, t2.level: 47.0
t1.level: 47.0, t2.level: 47.0
t1.level: 27.0, t2.level: 57.0
t1.level: 57.0, t2.level: 57.0
t1.level: 27.0, t2.level: 27.0
t1.level: 57.0, t2.level: 57.0
*/
Chapter_4 Exercise_4-1 Sum | BACK_TO_TOP | Exercise_4-3 |
Comments
Post a Comment