The trick is to use the classes without soiling the existing code.
1. Composition--simply create objects of your existing class inside the new class. Simply reusing the functionality of the code, not its form
2.inheritance--creates a new class as a type of an existing class. Take the form of the existing class and add code to it without modifying the existing class.
Inheritance is one of the cornerstones of object-oriented programming, and have additional implications that'll be Explor Ed in the polymorphism chapter.
Composition syntax
References initialized:
1. At the point the objects is defined
2. In the constructor for that class
3. Right before-actually need to use the object (lazy initialization)
4. Using instance Initialization
Such as:
public class Bath {
Private String S1 = "Happy"; Initialization at the point of definition
Private String s2,s3,s4;
Public Bath () {
S2 = "Happy"; In the constructor
}
{s3 = "Happy";} Instance initialization
Public String toString () {
Lazy initialization
if (S4 = = null) {
S4 = "Happy";
}
return S4;
}
}
Inheritance syntax
Super.methodname () Calling a method of the parent class
Initializing the base class
When you create an object of the derived class, it contains within it a subobject of the base class. This subobject are the same as if you had created a object of the base class by itself. It's just that from the outside, the subobject of the base class is wrapped within the Derived-class object.
Java automatically inserts calls to the Base-class constructor in the Derived-class constructor.
Constructors with arguments
The call to the Base-class constructor with arguments must explicit, and is the first thing you does in the Derived-class Co Nstructor, Etc:super (1)
Delegation
A third relationship, which is not directly supported by Java, is called delegation. This is midway between inheritance and composition.
member object in the class you ' re building (like composition), but at the same time you expost all the methods From the member object in your new class (like inheritance).
Combining composition and inheritance guaranteeing proper cleanup
If you want something cleaned-a class, you must explicitly write a special method to do it, and make sure that the Client programmer knows that they must call the This method.
On top of This--as described in the Erro handling with Exceptions chapter--you must guard against as exception by putting Such cleanup in a finally clause.
Note that in your cleanup method, you must also pay attention to the calling order for the Base-class and Member-object cl Eanup methods in case one subobject depends on another. In general, first perform all the cleanup work specific to your class, in the reverse order or Creationg. Then call the Base-class cleanup method.
The user can call the Finalize method of the object itself, but this call is a normal method call, independent of the object's destruction process
Name hiding
Overloading works regardless of whether the method was defined in the Base-class or the Derived-class
Overload overloading
Override Again, overwrite
Java SE5 has added the @Override annotation. Whne mean to override a method, can choose to add this annotation and the compiler would produce an error message I f you accidentally overload instead of overriding.
Choosing Composition vs. inheritance
Composition is generally used if you want the features of a existing class inside your new class, but isn't its interface . That's, you embed a object so this can use it to implement features in your new class, but the user of your new clas s sees the interface you ' ve defined for the new class RATHG than the interface from the embedded object. For the effect, you embed private objects of existing classes inside your new class.
Sometimes it makes sense to allow the class user to directly access the composition of your new class; That's is,to make the member objects public. When the user know your ' re assembling a bunch of parts, it makes the interface easier to understand
Example: Car, containing door (behavior: Open), Engine (behavior: Start)
Automobiles-doors-open (public gate)
Auto. Start (Private engine)
Note Keep in mind this in general you should make fields private.
When you inherit, the existing class and make a special version of it. In the general, this means, the taking a general-purpose class and specializing it for a particular need.
Composition:has-a relationship
Inheritance:is-a relationship
Interface:like-a relationship
Protected
This was private as far as the class user is concerned, but available to anyone who inherits from the class or anyone else The same package.
Upcasting
The most important aspect of inheritance are not so it provides methods for the new class. It ' s The relationship expressed between the new class and the base class.
Upcasting is always safe because you ' re going from a more specific type to a more general type.
You can also perform the reverse of upcasting, called downcasting, it's involves a dilemma that'll be examined Furth Er in the next chapter, and in the Type information chapter.
Composition vs. Inheritance Revisited
In object-oriented programming, the most likely the "to" you'll create and use code are by simply packaging data and method S together inti a class, and using object of that class. You'll also use existing class to build new classes with composition. Less frequently, and you'll use inheritance.
One of the clearest ways to determine whether your should use composition or inheritance are to ask whether you ' ll ever need To upcast from your new class to the base class. If you don't need to upcast and then you should look closely at whether you need inheritance.
The final keyword
Final can be used:for data, methods, and classes.
Final data
To tell the compiler, a piece of data is constant. A constant is useful for the reasons:
1. It can be a Compile-time constant this won ' t ever change.
2. It can be a value of initialized at run time, so you don ' t want changed.
In the case of a Compile-time constant, the compiler are allowed to ' fold ' the constant value into any calculations in whic H it ' s used; That's, the calculation can performed at compile time, eliminating some run-time overhead. In Java, these sorts of constants must is primitives and is expressed with the final keyword. A value must is given at the time of definition of such a constant.
A field that is both static and final have only one piece of storage the cannot be changed.
When final was used with object references rather than primitives, makes the reference a constant. Once the reference is initialized to a object, it can never be changed to point to another object. Howerver, the object itself can be modified.
private static final int i = 5; Compile-time
private final int i = 5; Comile-time
private static final int i = new Random (). Nextint (20); Run-time
private final int i = new Random (). Nextint (20); Run-time
Making references final seems less useful than Making primitives final.
Blank Finals
public class Blankfinal {
private final int i = 0; Initialized final
private final int J; Blank final
Public blankfinal (int jj) {
j = JJ; Initialize Blank Final
}
}
You ' re forced to perform assignments to finals either with a expression at the point of definition of the the field or in Eve Ry constructor.
Final arguments
Java allows arguments final by declaring them as such in the argument list. This means, that inside the method, you cannot, the change, the argument reference points to.
This feature was primarily used to pass data to anonymous inner classes
Final methods
There is and reasons for final methods.
1. To put a "lock" on the method to prevent any inheriting class from changing its meaning.
2. Efficiency. (Old, Java SE5 is considered by the compiler and JVM)
Final and private
Any private methods in a class is implicitly final. Because you can ' t access a private method, you can override it.
"Overriding" can only occur if something are part of the Base-class interface. (That is, the private method in the parent class and the subclass does not affect the immediate signature.) If a method is private, it isn ' t part of the Base-class interface.
Final classes
When you say a entire class is final, your state so you don ' t want to inherit from the This class or allow anyone else to does so.
Note that the fields of a final class can is final or not. The same rules apply to final in fields regardless or whether the class is defined as final. However, because it prevents inheritance, all methods in a final class is implicitly final, since there ' s no-to-overr IDE them.
Final Cautioninitialization and class loading
In general, you can say this "class code is loaded on the point of first use." This was usually when the first object of that class was constructed, but loading also occurs when a static field or static method is accessed.
The point's is also where the static initialization takes place. All the static objects and the static code block is initialized in textual order at the point of loading. The statics is initialized only once.
Initialization with Inheritancesummary
Both inheritance and composition allow you to create a new type from existing types. Composition reuses existing types as part of the underlying implementation of the new type, and inheritance reuses the int Erface.
With inheritance, the derived class have the Base-class interface, so it can be upcast to the base which are critical for PO Lymorphism.
When you set the out to design a system, it's important to realize this program development are an incremental process, just Li Ke human learning. It relies on experimentation; You can does as much analysis as you want, but you still won ' t know all the answers when you set out on a project. You'll have much more success-and more immediate feedback-if you start out to "grow" your project as an organic, evolution ary creature, rather than constructing it all at once like a glass-box skyscraper.
Thinking in Java,fourth Edition (Java programming Idea, Fourth edition) learning notes (eight) reusing Classes