Exercise 4-3 (Method call Aliasing)
Chapter_4 Exercise_4-2 | Exercise_4-4 |
Exercise 4-3 TIJ, p. 67
Exercise 4-3: (1) Create a class containing a float and use it to demonstrate aliasing during method calls.
Aliasing.java
import static java.lang.System.out;
class Tank
{
float level;
}
// aliasing during method call (pass arguments by reference)
public class Aliasing
{
static void println(Object obj) {out.println(obj);}
static void changeLevel(Tank t, float newLevel) {t.level = newLevel;}
public static void main(String[] args)
{
Tank t = new Tank();
println("t.level: " + t.level); // initialized to 0.0f (float)
t.level = 9; // int to float OK, no precision loss
println("t.level: " + t.level); // 9.0f (printed 9.0)
// changeLevel(t, 27.0); // compile error, precision loss (from double)
changeLevel(t, 27.0f); // f for float, aliasing (t sent by reference)
println("t.level: " + t.level); // 27.0
}
}
/*
javac Aliasing.java
java Aliasing
t.level: 0.0
t.level: 9.0
t.level: 27.0
*/
Chapter_4 Exercise 4-2 | BACK_TO_TOP | Exercise_4-4 |
Comments
Post a Comment