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.
- The object-oriented programming encapsulation principle promotes the integration of state with behavior.
- A class is a source code blueprint.
- Another name for a class instance is an object.
- Java supports four access levels for fields and methods.
- Another name for a read-only variable is a constant/final variable/final.
- Values passed to a method during a method call are known as arguments.
- Call-by-value passes a value to a method, and call-by-reference passes a reference.
- When only a single object can be created from a class, that class is known as a singleton class.
- Aggregation is a synonym for composition.
- The object-oriented programming inheritance principle promotes layered objects.
- Composition promotes has a relationships.
- A child class/derived class/subclass inherits fields and methods from a parent class/base class/superclass.
- If class
A
extends classB
, and classA
declares a method that has the same name, return type, and parameter list as classB
‘s method, classA
‘s method is said to override classB
‘s method. Object
is Java’s ultimate superclass.- Arrays are shallowly cloned.
- The object-oriented programming polymorphism principle promotes many forms.
- Class methods are statically bound to classes, and instance methods are dynamically bound to objects.
- Classes situated near the top of a class hierarchy represent generic/abstract entities, and classes lower in the class hierarchy represent specific/concrete entities.
- The
equals()
method defaults to comparing object references. - The
clone()
method throws aCloneNotSupportedException
object if it cannot clone an object. -
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
-
Which keyword has something to do with object serialization?
a)
transient
b)
volatile
c)
synchronized
d)
native
-
Which of the following keywords do you use to achieve implementation inheritance?
a)
implements
b)
extends
c)
super
d)
this
-
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
. -
Which method returns an object locked (behind the scenes) by static synchronized methods?
a)
toString()
b)
finalize()
c)
getClass()
d)
wait()
-
Note: Choice d is also tempting. However,
wait()
is not correct. If you examine the SDK documentation forObject
‘sgetClass()
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 bystatic synchronized
methods of the represented class.The same cannot be said for
wait()
. -
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
- True or false: Object-oriented programming emphasizes separating a program’s data from its functionality.
-
False
- True or false: You must declare class fields with the
static
keyword. -
True
- True or false: The integration of state and behaviors into objects is known as information hiding.
-
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
andprotected
limit field/method exposure, and that is known as information hiding. - True or false: When the JVM creates an object, it zeroes the memory assigned to each instance field.
-
True
- True or false: You can access local variables prior to specifying their declarations.
-
False
- True or false: You must initialize local variables before accessing them.
-
True
- True or false: Subclasses can override a superclass’s final methods.
-
False
- True or false: An enumerated type is a reference type with an unrestricted set of values.
-
False
- True or false: When returning a value from a method, that method must not have a void return type.
-
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.
- True or false: A class method cannot access an object’s instance fields.
-
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.
- 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. -
False
- True or false: If a class declares no constructors, the compiler generates an empty no-argument constructor.
-
True
- True or false: You cannot extend final classes.
-
True
- True or false: You can use keyword
super
to call a superclass constructor from any method. -
False
- True or false: You cannot make a field or method’s access level more restrictive in a subclass.
-
True
- True or false: Java supports multiple implementation inheritance.
-
False
- True or false: A subclass can directly access a superclass’s private fields.
-
False
- True or false: You can legally place code ahead of a constructor call (via either
this
orsuper
) in a constructor. -
False
- True or false: Arrays are objects.
-
True
- True or false: You can declare read/write variables in an interface.
-
False
- True or false: All method signatures in an interface have a public access level.
-
True
- True or false: A class that inherits an abstract method from a superclass and does not override that method is also abstract.
-
True
- True or false: You can declare field variables in methods.
-
False
Note: You declare field variables within classes, but not within methods. You declare local variables and parameter variables in methods.
- True or false: Java’s
new
keyword allocates memory for an object, and Java’sdelete
keyword releases that memory. -
False
- True or false: The
Object
class declares 11 methods. -
True
-
If a subclass constructor does not include a call to a superclass constructor (via
super
) or another subclass constructor (viathis
), what happens?The compiler inserts code into the subclass constructor to call the no-argument constructor in its superclass.
-
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 callsSup
‘s no-argument constructor. BecauseSup
does not explicitly declare that constructor,Sup
lacks a no-argument constructor — and the compiler reports an error. IfSup
did not declare any constructor, the compiler would generate a no-argument constructor forSup
, and there would be no problem. BecauseSup
declares aSup(int x)
constructor, there is a problem. Alternatively,Sub
should have aSub(int x)
constructor that callsSup(int x)
viasuper(x);
. -
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 theabstract
keyword. -
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.
-
List the four polymorphism categories.
The four polymorphism categories are coercion, overloading, parametric, and inclusion (subtype).
-
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. -
Must a subclass constructor always call a superclass constructor?
No. Sometimes, a subclass constructor uses keyword
this
to call another subclass constructor. -
Explain two uses for the
super
keyword.- Calling superclass constructors (from subclass constructors)
- Accessing superclass fields/calling superclass methods from subclass methods
-
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
, andC
are empty interfaces,interface X extends A, B, C { }
is legal. -
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. -
What are hash codes?
Hash codes are integers that uniquely identify objects.
-
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.
-
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.
-
Why can’t a class signature include both the
abstract
andfinal
keywords?A class signature cannot include both the
abstract
andfinal
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. -
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 declareclass Account {}
inAccount.java
?No. You can choose any filename for the source file in which you declare the nonpublic class.