Study guide: Class and object initialization

Brush up on Java terms, learn tips and cautions, review homework assignments, and read Jeff’s answers to student questions

Glossary of terms

class block initializer
An initializer that makes complex class initialization possible. A class block initializer consists of the static keyword, an open brace character, initialization code, and a close brace character.
class field initializer
An initializer that makes simple class field initialization possible. A class field initializer combines an expression with an assignment operator, which evaluates the expression and assigns its result to a class field after a class loads and before any of its methods execute.
object block initializer
An initializer that makes complex object initialization possible. An object block initializer consists of an open brace character, initialization code, and a close brace character.
object field initializer
An initializer that makes simple object field initialization possible. An object field initializer combines an expression with an assignment operator, which causes the expression to evaluate and its result to assign to an object field during the constructor call portion of an object’s creation.

Tips and cautions

These tips and cautions will help you write better programs and save you from agonizing over error messages produced by the compiler.

Tips

  • If you are interested in learning more about class and object initialization at the JVM level, investigate the SDK’s javap program. That program generates a disassembly of Java class files.

Cautions

  • Avoid accessing subclass fields from superclass initializers. During superclass initialization, subclass fields have not initialized and only contain default values.
  • Avoid introducing constructors that call each other. Calling either constructor results in a stack overflow and does not execute object initializers.

Miscellaneous notes and thoughts

Java’s standard class library contains many examples of class block initializers. In addition to Java Database Connectivity’s (JDBC) use of that feature, Object uses a class block initializer to register its native methods (such as clone(), getClass(), and hashCode()) with the JVM. The following Object code fragment takes care of that task:

private static native void registerNatives ();
static
{
   registerNatives ();
}

And what is a native method? Keep reading Java 101 to find out.

Homework

Trace the initialization process through the Employees source code below. You should end up with a numbered list that includes all initialization steps until the last Accountant object finishes initializing.

Employees.java

// Employees.java
class Employee
{
   private String name;
   private double salary;
   static int count;
   static double bonus;
   Employee (String name, double salary)
   {
      this.name = name;
      this.salary = salary;
      if (this instanceof Accountant)
          this.salary += bonus;
   }
   static
   {
      // Pretend to load bonus from a database.
      bonus = 500.0;
   }
   {
      if (count > 5)
          bonus = 0.0;
      count++;
   }
   String getName ()
   {
      return name;
   }
   double getSalary ()
   {
      return salary;
   }
}
class Accountant extends Employee
{
   Accountant (String name, double salary)
   {
      super (name, salary);
   }
}
class Employees
{
   public static void main (String [] args)
   {
      String [] names =
      {
         "John Doe",
         "Jane Smith",
         "Jack Jones",
         "Bob Smyth",
         "Alice Doe",
         "Janet Jones"
      };
      double [] salaries =
      {
         40000.0,
         50000.0,
         30000.0,
         37500.0,
         52000.0,
         47000.0
      };
      for (int i = 0; i < names.length; i++)
           if (i < 3)
           {
               Employee e = new Employee (names [i], salaries [i]);
               System.out.println ("Name = " + e.getName ());
               System.out.println ("Salary = " + e.getSalary ());
           }
           else
           {
               Accountant a = new Accountant (names [i], salaries [i]);
               System.out.println ("Name = " + a.getName ());
               System.out.println ("Salary = " + a.getSalary ());
           }
   }
}

Answers to the Java 101 Challenge

Last month, I issued a challenge quiz as a way of reviewing material presented in the “Object-Oriented Language Basics” series. The following three entrants emerged as the winners:

  • Jason Davies
  • David Hibbs
  • Gagan Indus

Jason, David, and Gagan were the first three challenge contestants to answer all questions correctly. Congratulations to the three of you! You will each receive a JavaWorld sweatshirt. To those of you who entered the contest but did not win, my heartfelt thanks. You are also winners.

Below you will find the answers to the Java 101 Challenge. Each answer is shown in red, and I include a forward slash character in those fill-in-the-blank answers that indicate a choice between multiple possibilities.

  1. The object-oriented programming encapsulation principle promotes the integration of state with behavior.
  2. A class is a source code blueprint.
  3. Another name for a class instance is an object.
  4. Java supports four access levels for fields and methods.
  5. Another name for a read-only variable is a constant/final variable/final.
  6. Values passed to a method during a method call are known as arguments.
  7. Call-by-value passes a value to a method, and call-by-reference passes a reference.
  8. When only a single object can be created from a class, that class is known as a singleton class.
  9. Aggregation is a synonym for composition.
  10. The object-oriented programming inheritance principle promotes layered objects.
  11. Composition promotes has a relationships.
  12. A child class/derived class/subclass inherits fields and methods from a parent class/base class/superclass.
  13. If class A extends class B, and class A declares a method that has the same name, return type, and parameter list as class B‘s method, class A‘s method is said to override class B‘s method.
  14. Object is Java’s ultimate superclass.
  15. Arrays are shallowly cloned.
  16. The object-oriented programming polymorphism principle promotes many forms.
  17. Class methods are statically bound to classes, and instance methods are dynamically bound to objects.
  18. Classes situated near the top of a class hierarchy represent generic/abstract entities, and classes lower in the class hierarchy represent specific/concrete entities.
  19. The equals() method defaults to comparing object references.
  20. The clone() method throws a CloneNotSupportedException object if it cannot clone an object.
  21. When declaring a field, which of the following access-level specifier keywords would you use so that only classes in the same package as the class that declares the field can access that field?

    a) public

    b) private

    c) protected

    d) none of the above

  22. Which keyword has something to do with object serialization?

    a) transient

    b) volatile

    c) synchronized

    d) native

  23. Which of the following keywords do you use to achieve implementation inheritance?

    a) implements

    b) extends

    c) super

    d) this

  24. Note: It is tempting to think that the correct choice is a. That is not the correct choice, however, because you achieve implementation inheritance by extending classes with the keyword extends.

  25. Which method returns an object locked (behind the scenes) by static synchronized methods?

    a) toString()

    b) finalize()

    c) getClass()

    d) wait()

  26. Note: Choice d is also tempting. However, wait() is not correct. If you examine the SDK documentation for Object‘s getClass() method, you will discover that it says the following:

    Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

    The same cannot be said for wait().

  27. According to Sun’s Java 2 SDK, how many public classes can be declared in a source file?

    a) 1

    b) 0

    c) as many as desired

    d) no more than 1 public class and 1 public interface

  28. True or false: Object-oriented programming emphasizes separating a program’s data from its functionality.
  29. False

  30. True or false: You must declare class fields with the static keyword.
  31. True

  32. True or false: The integration of state and behaviors into objects is known as information hiding.
  33. False

    Note: Information hiding is not a synonym for encapsulation. Encapsulation refers to the act of combining state and behavior (through instance fields and instance methods) into single entities (known as objects). Information hiding determines how accessible parts of an object are to other objects. Keywords like private and protected limit field/method exposure, and that is known as information hiding.

  34. True or false: When the JVM creates an object, it zeroes the memory assigned to each instance field.
  35. True

  36. True or false: You can access local variables prior to specifying their declarations.
  37. False

  38. True or false: You must initialize local variables before accessing them.
  39. True

  40. True or false: Subclasses can override a superclass’s final methods.
  41. False

  42. True or false: An enumerated type is a reference type with an unrestricted set of values.
  43. False

  44. True or false: When returning a value from a method, that method must not have a void return type.
  45. True

    Note: You generally use a return statement to return a value from a method. You could also return a value through a parameter that contains a reference to an object, provided the object has a method that can be called. In that case, the method could have a void return type. However, because return statements are more commonly used, the correct answer to this question is true.

  46. True or false: A class method cannot access an object’s instance fields.
  47. True

    Note: Unfortunately, this question was not as clear as it could have been. A class method cannot directly access instance fields from within the same class. It must refer to some object to indirectly access instance fields.

  48. True or false: The keyword this can be used in any method to call a constructor that resides in the same class as that method.
  49. False

  50. True or false: If a class declares no constructors, the compiler generates an empty no-argument constructor.
  51. True

  52. True or false: You cannot extend final classes.
  53. True

  54. True or false: You can use keyword super to call a superclass constructor from any method.
  55. False

  56. True or false: You cannot make a field or method’s access level more restrictive in a subclass.
  57. True

  58. True or false: Java supports multiple implementation inheritance.
  59. False

  60. True or false: A subclass can directly access a superclass’s private fields.
  61. False

  62. True or false: You can legally place code ahead of a constructor call (via either this or super) in a constructor.
  63. False

  64. True or false: Arrays are objects.
  65. True

  66. True or false: You can declare read/write variables in an interface.
  67. False

  68. True or false: All method signatures in an interface have a public access level.
  69. True

  70. True or false: A class that inherits an abstract method from a superclass and does not override that method is also abstract.
  71. True

  72. True or false: You can declare field variables in methods.
  73. False

    Note: You declare field variables within classes, but not within methods. You declare local variables and parameter variables in methods.

  74. True or false: Java’s new keyword allocates memory for an object, and Java’s delete keyword releases that memory.
  75. False

  76. True or false: The Object class declares 11 methods.
  77. True

  78. If a subclass constructor does not include a call to a superclass constructor (via super) or another subclass constructor (via this), what happens?

    The compiler inserts code into the subclass constructor to call the no-argument constructor in its superclass.

  79. What is wrong with the following code fragment?

    class Sup
    {
       Sup (int x)
       {
       }
    }
    class Sub extends Sup
    {
    }
    

    The compiler generates a no-argument constructor for Sub that calls Sup‘s no-argument constructor. Because Sup does not explicitly declare that constructor, Sup lacks a no-argument constructor — and the compiler reports an error. If Sup did not declare any constructor, the compiler would generate a no-argument constructor for Sup, and there would be no problem. Because Sup declares a Sup(int x) constructor, there is a problem. Alternatively, Sub should have a Sub(int x) constructor that calls Sup(int x) via super(x);.

  80. Is there anything wrong with the following code fragment?

    abstract void hello () 
    {
       System.out.println ("Hello")
    }
    

    The code fragment is missing a semicolon character after System.out.println ("Hello"). Furthermore, the compiler does not allow a code body if a method signature includes the abstract keyword.

  81. Why would you use interfaces?

    You would use interfaces to factor out common behaviors from multiple class hierarchies, to introduce types without assigning implementations to those types, or to provide a workaround to Java’s lack of support for multiple implementation inheritance.

  82. List the four polymorphism categories.

    The four polymorphism categories are coercion, overloading, parametric, and inclusion (subtype).

  83. Suppose you create an object from a superclass and assign that object’s reference to a superclass variable. Suppose you cast that variable’s type from the superclass type to a subclass type before accessing a subclass field or calling a subclass method. What happens?

    Although the compiler compiles the code, the JVM throws a ClassCastException object — because the object contains no subclass fields or methods.

  84. Must a subclass constructor always call a superclass constructor?

    No. Sometimes, a subclass constructor uses keyword this to call another subclass constructor.

  85. Explain two uses for the super keyword.

    1. Calling superclass constructors (from subclass constructors)
    2. Accessing superclass fields/calling superclass methods from subclass methods
  86. A class can only extend one superclass. Is an interface subject to the same restriction (that is, can an interface only extend a single superinterface)?

    No. An interface can extend more than one superinterface. For example, assuming A, B, and C are empty interfaces, interface X extends A, B, C { } is legal.

  87. By default, what does an object’s toString() method return?

    An object’s toString() method defaults to returning an object’s class name, followed by an @ character, which is then followed by the object’s hash code.

  88. What are hash codes?

    Hash codes are integers that uniquely identify objects.

  89. When does method overloading fail?

    Method overloading fails when only method return types are changed. Overloading also fails when the compiler detects ambiguous argument references. (See the OverloadFailure program source code, below.)

    // OverloadFailure.java
    class BaseClass
    {
    }
    class DerivedClass extends BaseClass
    {
       void method (BaseClass b, DerivedClass d)
       {
       }
       void method (DerivedClass d, BaseClass b)
       {
       }
    }
    class OverLoadFailure
    {
       public static void main (String [] args)
       {
          DerivedClass d = new DerivedClass ();
          // Should method (BaseClass b, DerivedClass d) or 
          // method (DerivedClass d, BaseClass b) be called?
          d.method (d, d);
       }
    }
    
    

    Note: Either solution (return type change only or ambiguous references) answers this question.

  90. Describe the difference between shallow cloning and deep cloning.

    Shallow cloning only produces a copy of primitive type field values, whereas deep cloning also produces copies of all objects referenced from reference type fields.

  91. Why can’t a class signature include both the abstract and final keywords?

    A class signature cannot include both the abstract and final keywords because the result is meaningless. You cannot create an object from such a class, and there is no way to extend the class for creating an object from a subclass.

  92. If you do not declare a class to be public, must you declare it in a file whose filename matches the class name? For example, must you declare class Account {} in Account.java?

    No. You can choose any filename for the source file in which you declare the nonpublic class.

Source: www.infoworld.com