2.9 KiB
Exercise 1
- What is the relationship between the two local variables called temp?
- What is the scope of each of these two variables?
- Suppose now that we introduce a field called temp.
- What is the scope of each of the local variables now ?
- What is the scope of the field called temp ?
- How would we access this field's value from within report()?
public class ArrayHwk1
{
// constructor here
public void report()
{
double temp = rainiest();
System.out.println(′′Most rain: ′′ + temp + ′′mm′′);
// other code here
}
private double rainiest()
{
double temp;
// code to find most rainfall here and to store
// it in the local variable temp
return temp;
}
// other code here
}
- There is no relationship between 2 local variables.
- The lifetime of both local variables, temp, is the method in which they are created.
- .
- The scope is unchanged, since the local variables are still created in the method.
- The field variable's scope is the entire class, aside from where the local variables are created.
- By using this.temp, we can access the class's field variable
Exercise 2
class Param1
{
public final float fixed = 50;
public double a;
private int b;
public float c;
// constructor here
public float method1(int z)
{
return (float) z; //H
}
private void method2(double y)
{
c = y; //I double to float error
}
public int method3()
{
return b; //J
}
}
tester.fixed = 25; // Statement A fixes is final, immutable. tester.b = 50; // Statement B b is private, cannot directly modify. tester.c = 5.0; // Statement C c is a float, cannot assign double. int y = tester.method1(); // Statement D logic error: not given parameter, cannot assign float to int. tester.method2(10.0f); // Statement E method2 is private. float y = tester.method3(); // Statement F no error, implicit typecast int to float. double y = tester.method1(30); // Statement G no error, implicit typecast int to float to double.
Exercise 3
class Param1
{
private int score;
// default constructor here
public void method1(int y)
{
score = y;
}
public int getScore()
{
return score;
}
}
Param1 q1 = new Param1(); q1.method1(100); System.out.println(q1.getScore());```
score = 100
class Param2
{
public int x;
// default constructor here
public void method1(int y)
{
x = 4*y;
}
public int getX()
{
return x;
}
}
Param2 q2 = new Param2(); int y = 25; // Local Variable. q2.method1(y); System.out.println(y); System.out.println(q2.getX());
y = 25
x = 100
class Param3
{
public int x;
// default constructor here
private void increase(int p)
{
x = x*p;
}
public void calculateX(int y)
{
increase(y);
}
public int getX()
{
return x;
}
}
Param3 q3 = new Param3(); q3.x = 5; q3.calculateX(7); increase(7) -> x(5) = x(5) * 7 -> 5 * 7 = 35 System.out.println(q3.getX());
x = 35