Thinking in Java Fourth Edition Bruce Eckel Chapter 4 Exercise 14

 Exercise 14: Create a class with a static String field that is initialized at the point of definition, and another one that is initialized by the static block. Add a static method that prints both fields and demonstrates that they are both initialized before they are used.

class Go
{
    static String s1 = "run";
    static String s2, s3;
    static
    {
        s2 = "drive car";
        s3 = "fly plane";
        System.out.println("s2 & s3 initialized");
    }
    static void how()
    {
        System.out.println(s1 + " or " + s2 + " or " + s3);
    }
    Go()
    {
        System.out.println("Go()");
    }  
}

public class ExplicitStaticEx
{
    public static void main(String[] args)
    {
        System.out.println("Inside main()");
        Go.how();
        System.out.println("Go.s1: " + Go.s1);     
    }
    static Go g1 = new Go();
    static Go g2 = new Go();
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *