Java Study Notes 6-reusing classes

Source: Internet
Author: User
Reusing classes

There are two reusing classes Methods: composition and inheritance ).

Composition vs. Inheritance

1. Differences:
Composition:
*. Have-,
*. The old class function is reused:
*. Do not want upcasting.
*. Summary: In general, synthesis is used for the new class to use the functions of the old class, rather than the occasion of its interface. That's it.
It means to embed an object and use it to implement the functions of the new class, but the user sees the new class
Interface, rather than the interface of the embedded object. Therefore, you have to embed private in the new class.
.)
Inheritance:
*. Is-,
* The interface of the old class is reused,
*. Want to upcasting
*. Summary: The Inheritance method is to modify the existing classes to obtain a special version. In short,
You need to transform a more abstract class into a class suitable for certain requirements. Think about it
It is meaningless to use vehicle (vehicle) objects to synthesize a car. A car does not contain vehicle,
It is vehicle. Inheritance expresses a "is-a" relationship, while synthesis expresses a "has-a" relationship.

2. merging or inheritance. Further exploration:
In the face object programming, the most common programming and code methods are data and methods.
It is encapsulated into a class, and then the class object is used. You can also combine the existing
To create a new class. Inheritance is not commonly used. Therefore, although the learning in OOP
Inheritance occupies a very important position, but this is not to say that you can abuse it everywhere. On the contrary
When using inheritance, you should be as conservative as possible, only when it brings obvious benefits
Wait, you can use it. When determining whether to use merging or inheritance, it is the easiest way to do this.
The method is to ask if you will upload the new class to the base class. If you must upload the file
It is mandatory. If you do not need to upload the file, you should check whether it should be inherited.
The next section (polymorphism) explains why to upload, but if you still remember to ask yourself <B> "I need
Do you want to upload ?" </B>, then you have a good job to help you determine whether to use merging or inherit.
Yes.

3. Summary:
Inheritance and Chengdu allow you to create new classes based on existing classes. But in general,
Merging is to reuse existing classes as part of the underlying implementation of new classes, while inheritance is to reuse them.
Interface. Because the derived class has the interface of the base class, it can be uploaded (upcast) to the base class,

Although object-oriented programming emphasizes inheritance repeatedly, when you design it
In this case, we should first consider merging and use inheritance only when necessary. Synthesis will work better
Active. In addition, the member can use the object of the inherited class, so that you can replace
The specific type and behavior of some members. Therefore, the behavior of the merged object can also be obtained.
To change.

All non-primitive objects have a tostring () method. When the compiler needs a string but it is an object,
The compiler automatically calls this method.

"" + X can automatically convert X to string (if X is a non-primitive object, the tostring method will be called)

Unit Test
You can create a main () for each class, and this is also a recommended programming method, because in this way, the test code can be put into the class.
Even if the program contains many classes, it will only call the main () method of the class you provided in the command line.
(As long as main () is public, it doesn't matter if the class is public .)
This method of placing a main () in each class makes unit testing easier.
After testing, you do not have to remove main (); leave it for future testing.

There is a general principle in inheritance design, that is, to set data to private and to set all methods to public.

Should Private or protected be used in inheritance?
The best practice is to set <B> data member (fields) to private </B>,
Then, <B> use the method with the protected permission </B> to control the access permission of the inherited class:

The object (this) of the new class contains the subobject (Super) of the base class ):
From the perspective of outsiders, the new class has the same interface as the old class, and there may be
Some of its own methods and data. However, inheritance is not just an interface for copying base classes.
When you create a derived class object, this object also contains a base class subobject ).
This sub-object is similar to the object created by the base class.
From the outside, this sub-object is wrapped in the object of the derived class.

The compiler will force you to put the base class constructor call -- Super (...) in the constructor of the derived class.
The beginning of the number. That is to say, there cannot be anything before it.

Try {
...
} Finally {
...
}
Try indicates that the following Program (limited by curly brackets) is a protected area (guarded region) that requires special attention ).
The special concern is that, no matter how you exit the try block, you must execute the finally clause following the protected area.
(For Exception Handling, there may be many abnormal exit from the try block .) Here

In many cases, cleaning is not a problem; leave it to the garbage collector. However
If you want to do it yourself, you have to work hard and be especially careful, because
No one can help you with garbage collection. The Garbage Collector may never start. Even if it
Once started, you cannot control the order of collection. <B> it is best not to rely on the Garbage Collector for any
It has nothing to do with memory reclaim. </B> if you want to clean up, you must write the cleaning method by yourself.
Use finalize ().

Progressive Development
One of the advantages of inheritance is that it supports progressive development ).
When new code is added, it does not bring bugs to the Old Code. In fact, all new bugs are circled in the new Code.
Inherit existing classes that can work normally, and then add fields and methods (and re-define existing methods ),
You don't need to modify the old code that may be used by others, so it won't cause bugs. Once a bug is found, you
It must be in the new Code. Compared with modifying the old Code, the new Code is much shorter and easier to read.

Although inheritance is a very useful technique in the pilot phase, when the project enters the stable phase
Then you have to look at the class inheritance system with a new perspective. You need to compress it
A logical structure. The program should not be switched around bits. It should start from the problem space and express a solution by creating and controlling various objects.
Problem Method.

Upload (upcasting)
Inheritance expresses the relationship between the new class and the base class: "The derived class is a type of base class".

A derived class is a superset of the base class. Some methods of the base class have a derived class. Therefore, messages sent to the base class can also be sent to the derived class.

Final
Fields:
1. Primitive: The value cannot be modified.
2. Non-primitive (Object Reference): cannot point to other objects
Method:
1. Disable overriding. It also indicates that this method does not use late binding.
2. Efficiency (not useful)
Class:
To prevent inheritance. The fields of final class can be either final or not,
But all methods are implicitly final (because the class cannot be inherited, the method cannot be rewritten)

Arraylist replaces Vector
Hashmap replaces hashtable

Override: derived class redefines a method with the same name as the base class and the same parameter list as non-private. It is the basis for implementing polymorphism.
Overload: whether in derived class or base class, methods with the same name are visible as long as the parameter list is different and will not be overwritten.

Note:Only the items in the basic class interface (Private method does not belong to the interface) can be overwritten)
If the method is private, it does not belong to the interface of the base class. It can only be regarded as a code hidden by the class, with the same name.
If you create a public, protected, or package permission method with the same name in the derived class
There is no contact for methods with the same name. You didn't override that method. you just created a new method.

Don't fall into the trap of premature code optimization. Assume that you have a running speed
It is hard to say whether final can be used to solve the problem.
However, we can use profiling as a tool that can help you improve program running speed.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.