Exercise 3-7 (static class Incrementable)

Chapter_3     Exercise_3-6 Exercise_3-8







Exercise 3-7     TIJ, p. 61


Exercise 3-7: (1) Turn the Incrementable code fragments into a working program.




Increment.java     TIJ, p. 51-52


public class Increment
{
static class StaticTest // inner static class
{
static int i = 47;
}

static class Incrementable // inner static class
{
static void increment()
{ // access static field in a static context:
StaticTest.i++;
}
}

public static void main(String[] args)
{
StaticTest st1 = new StaticTest();
StaticTest st2 = new StaticTest();
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
Incrementable sf = new Incrementable();
sf.increment();
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
Incrementable.increment();
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
new Incrementable().increment();
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
// access static field in a static context, main():
StaticTest.i++;
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
new StaticTest().i++;
System.out.println("st1.i = " + st1.i);
System.out.println("st2.i = " + st2.i);
}
}
/*
javac Increment.java
java Increment
st1.i = 47
st2.i = 47
st1.i = 48
st2.i = 48
st1.i = 49
st2.i = 49
st1.i = 50
st2.i = 50
st1.i = 51
st2.i = 51
st1.i = 52
st2.i = 52
*/









Chapter_3     Exercise_3-6 BACK_TO_TOP Exercise_3-8



Comments

Popular posts from this blog

Contents