Inheritance is a powerful way to achieve code reuse, but it is not always the best tool for the job. Used inappropriately, it leads to fragile software. Unlike method invocation, inheritance violates encapsulation. In other words, a subclass depends on the implementation details of its superclass for its proper function. A class B should extend […]
Classes and Interfaces
Classes and interfaces lie at the heart of Java programming language. They are its basic units of abstraction. The language provides many powerful elements that you can use to design classes and interfaces.
Minimize mutability
An immutable class is a simply class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. Don’t provide any methods that modify the object’s state (known as mutators) Ensure that the class can’t be extended. This […]
In public classes, use accessor methods, not public-fields
Occasionally, you may be tempted to write degenerate classes that server no purpose other than to group instance fields: //Degenerate classes like this should not be public! class Point { public long x; public long y; } Because the data fields of such classes are accessed directly, these classes do not offer the benefits of […]
Minimize the accessibility of classes and members
The single most important factor that distinguishes a well-designed module a poorly designed one is the degree to which the modules hides its internal dara and implementation details. A well-designed module hides all of its implementation details, cleanly separating its API from its implementation. Information hiding doesn’t cause on itself good performance, it enables effective […]