Java Reference
In-Depth Information
private int age;
...
}
13.10.5 Completeness
Classes are designed for use by many different customers. In order to be useful in a wide range
of applications, a class should provide a variety of ways for customization through properties
and methods. For example, the String class contains more than 40 methods that are useful
for a variety of applications.
13.10.6 Instance vs. Static
A variable or method that is dependent on a specific instance of the class must be an instance
variable or method. A variable that is shared by all the instances of a class should be declared
static. For example, the variable numberOfObjects in CircleWithPrivateDataFields
in Listing 9.8 is shared by all the objects of the CircleWithPrivateDataFields class
and therefore is declared static. A method that is not dependent on a specific instance
should be defined as a static method. For instance, the getNumberOfObjects() method
in CircleWithPrivateDataFields is not tied to any specific instance and therefore is
defined as a static method.
Always reference static variables and methods from a class name (rather than a reference
variable) to improve readability and avoid errors.
Do not pass a parameter from a constructor to initialize a static data field. It is better to
use a setter method to change the static data field. Thus, the following class in (a) is better
replaced by (b).
public class SomeThing {
private int tl;
private static int t2;
public class SomeThing {
private int tl;
private static int t2;
public SomeThing( int tl, int t2) {
...
}
}
public SomeThing( int tl) {
...
}
public static void setT2( int t2) {
SomeThing.t2 = t2;
}
}
(a)
(b)
Instance and static are integral parts of object-oriented programming. A data field or
method is either instance or static. Do not mistakenly overlook static data fields or methods.
It is a common design error to define an instance method that should have been static. For
example, the factorial(int n) method for computing the factorial of n should be defined
static, because it is independent of any specific instance.
A constructor is always instance, because it is used to create a specific instance. A static
variable or method can be invoked from an instance method, but an instance variable or
method cannot be invoked from a static method.
common design error
13.10.7 Inheritance vs. Aggregation
The difference between inheritance and aggregation is the difference between an is-a and a
has-a relationship. For example, an apple is a fruit; thus, you would use inheritance to model
the relationship between the classes Apple and Fruit . A person has a name; thus, you would
use aggregation to model the relationship between the classes Person and Name .
 
 
Search WWH ::




Custom Search