CH 08
CH 08
occurred.
Composition—a capability that allows a class to have references to
detail.
Show how to organize classes in packages to help manage large
◦ Called the public services or the public interface that the class provides to its
clients.
the class body, using the same initialization syntax as with a local
variable.
IllegalArgumentException
◦ Notifies the client code that an invalid argument was passed to the method.
◦ Can use try...catch to catch exceptions and attempt to recover from them.
◦ The class instance creation expression in the throw statement creates a new
object of type IllegalArgumentException. In this case, we call the
constructor that allows us to specify a custom error message.
◦ After the exception object is created, the throw statement immediately
terminates method setTime and the exception is returned to the calling
method that attempted to set the time.
private.
The actual data representation used within the class is of no concern to
tasks.
◦ For this reason, the class’s private variables and private methods (i.e., its
implementation details) are not accessible to its clients.
private class members are not accessible outside the class.
declarations, the compiler places both class files for those classes in the
same directory.
A source-code file can contain only one public class—otherwise, a
package.
as a delegating constructor
Makes the class easier to maintain and modify
◦ If we need to change how objects of class Time2 are initialized, only the
constructor that the class’s other constructors call will need to be modified
constructor’s body.
Using this in method-call syntax as the first statement in a
However, consider changing the representation of the time from three int values
methods.
relationship.
Example: An AlarmClock object needs to know the current time
and the time when it’s supposed to sound its alarm, so it’s
reasonable to include two references to Time objects in an
AlarmClock object.
be overloaded.
For every enum, the compiler generates the static method
class Test {
// Static variable
static int i;
// Test class
class GFG {
public static void main(String args[]) {
// Although we don't have an object of Test, static
// block is called automatically.
System.out.println(Test.i);
}
}
© Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved.
8.11b static Initialization Block (cont.)
• The static block only gets called once, when the class itself is initialized, no
matter how many objects of that type you create.
• We can also create a non-static initialization block, which is executed each time
an object is created.
• No matter which constructor of the class is called, the non-static
initialization block is called for every object.
The non-static block:
{
// can access both static and non-static members
}
• Gets called every time an instance of the class is constructed.