Java three major features--inheritance

Source: Internet
Author: User

Let's look at an example before we explain it.

Husband.java

 Public class Husband {    private  String name;     Private String sex;    privateintage;     Private Wife Wife;     // getter and setter methods for omitting attributes }

Wife.java

 Public class Wife {    private  String name;     Private int Age ;     Private String sex;     Private Husband Husband;     // getter and setter methods for omitting attributes }

From here we can see, Wife, husband two classes in addition to their respective husband, Wife the rest of the same, as a want to maximize the reuse of code we are not able to endure such a repetition of code, if another small three, small four, small five ... Are we going to write that too? So how do we achieve the reusability of these classes? Use Inheritance!!

First we leave the world of software programming, and from common sense we know that husbands, wives, small three, small four ... they are all human beings, and they all have similarities, names, ages, genders, heads and so on, and they are able to eat, walk, talk and so on in common behavior, So from here we can find that they all own the attributes and behaviors of human beings, as well as the attributes and behaviors inherited from people.

From the above we can basically understand the concept of inheritance, inheritance is derived from the existing classes of new classes, the new class can absorb the existing classes of data properties and behavior, and can expand the new capabilities. Inheritance is the technique of building a new class using the definition of an existing class, and the definition of a new class can add new data or new functionality, or it can use the functionality of the parent class, but not selectively inherit the parent class. By using inheritance, we can easily reuse the previous code, which can greatly improve the efficiency of development.

Look at the following code, first define the parent class

Person.java

 Public class Person {    private  String name;     Private String sex;     Private int Age ;}

Husband.java

 Public class extends Person {    private  Wife Wife;     // getter and setter methods for omitting attributes }

Wife.java

 Public class extends Perso {    private  Husband Husband;     // getter and setter methods for omitting attributes }

After using inheritance for wife and husband, we can clearly see their relationship in addition to the reduction in the amount of code.

Inheritance describes the relationship of "is-a", if there are two objects A and B, if it can be described as "A is B", you can represent a inherits B, where B is referred to as the parent or superclass of the inheritors. A is an inheritor, called a subclass, or a derived class.

In fact, the successor is the specialization of the successor, in addition to having the characteristics of the successor, but also has its own unique characteristics. For example, cats have the characteristics of catching mice, climbing trees and other animals. At the same time in the inheritance relationship, the successor can be completely replaced by the successor, and vice versa, for example, we can say that the cat is an animal, but can not say that the animal is the cat is the truth, in fact, for this we call it "upward transformation", described below.

Inheritance defines how classes are associated with each other and share attributes. For several identical or similar classes, we can abstract out their common behavior or attributes and define them as a parent class or superclass, and then inherit the parent class with these classes, and they can not only own the properties of the parent class, but also define their own unique properties or methods.

At the same time, you need to remember three words when using inheritance:

1. Subclasses have properties and methods that are not private to the parent class.

2, subclasses can have their own properties and methods, that is, subclasses can extend the parent class.

3. Subclasses can implement the methods of the parent class in their own way. (Introduction later).

In summary, the use of inheritance does have many advantages, in addition to the common attributes of all subclasses into the parent class, to implement code sharing, avoid duplication, but also to make the implementation of the extension inheritance is relatively simple.

There must be three things about inheritance: constructors, protected keywords, and upward transformation.

Constructors

By the preceding we know that subclasses can inherit the properties and methods of the parent class, except for those private ones, which are---constructors that the subclass cannot inherit. For a constructor, it can only be called, not inherited. Call the construction method of the parent class we can use Super ().

For subclasses, the proper initialization of their constructors is important when and only if there is only one method to guarantee this: the parent class constructor is called in the constructor to complete the initialization, and the parent class constructor has all the knowledge and the ability to perform the initialization of the parent class.

classPerson {protectedString name; protected intAge ; protectedString sex; Person () {System.out.println ("Person constrctor ..."); }}  Public classHusbandextendsPerson {PrivateWife Wife; Husband () {System.out.println ("Husband Constructor ..."); }     Publicstaticvoid Main (string[] args) {Husband Husband=NewHusband (); }}
Output: Person  constrctor ...  

As you can see from this example, the build process is spreading from the parent class "outward", that is, starting with the parent class to complete the construction at the sub-class level. And we don't show the constructor that references the parent class, which is the smart thing about Java: The compiler will call the constructor of the parent class by default for the child class.

However, this default call to the constructor of the parent class is a prerequisite: the parent class has a default constructor. If the parent class does not have a default constructor, we will have to show the use of super () to call the parent class constructor, or the compiler will error: Cannot find a constructor that conforms to the parent class.

classPerson {protectedString name; protected intAge ; protectedString sex; Person (String name) {System.out.println ("Person constrctor-----" +name); }}  Public classHusbandextendsPerson {PrivateWife Wife; Husband () {Super("Show");//without this line of code, the compiler implicitly calls the parent class's parameterless construct by default, but the parent class does not have a parameterless construct and can only display the argument constructs of the calling parent classSystem.out.println ("Husband Constructor ..."); }     Public Static voidMain (string[] args) {Husband Husband=NewHusband (); }}

Output:  

In summary: For inheritance, subclasses call the parameterless constructor of the parent class by default, but if the parent class does not have a parameterless constructor by default, the subclass must display the constructor for the specified parent class, and must be the first thing to do in the subclass constructor (the first line of code).

protected Keywords

The private access modifier is the best choice for encapsulation, but this is based on the ideal world, and sometimes we need it: we need to hide something as close to the world as possible, but still allow members of the subclass to access it. This time you need to use the protected.

For protected, he is private for the class user, but he is accessible to any subclass that inherits from this class, or any other class that is in the same package.

classPerson {PrivateString name; Private intAge ; PrivateString sex; protectedString GetName () {returnname; }    protected voidsetName (String name) { This. Name =name; }     PublicString toString () {return"This name is" +name; }    /**omit other Setter, getter method **/} Public classHusbandextendsPerson {PrivateWife Wife;  PublicString toString () {SetName ("Show");//call the parent class's SetName ();        return Super. toString ();//Call the ToString () method of the parent class} publics taticvoidMain (string[] args) {Husband Husband=NewHusband ();    System.out.println (Husband.tostring ()); }}
Output: This  name is show

As you can see from the example above, the subclass husband can obviously call SetName () of the parent class person.

Although you can use the protected access modifier to restrict access to the properties and methods of the parent class, it is best to keep the property private (we should consistently keep changing the underlying implementation) and control the access rights of the inheritors of the class through the protected method.

Upward Transformation

In the above inheritance we talked about inheritance as a is-a relationship, cats inherit from animals, so we can say that cats are animals, or that cats are a kind of animals. This way the cat is seen as an animal or upward transformation. As follows:

classPerson { Public voiddisplay () {System.out.println ("Play person ..."); }    Static voiddisplay (person person) {person.display (); }}  Public classHusbandextendsPerson { Publicstaticvoid Main (string[] args) {Husband Husband=NewHusband (); Person.display (husband); //Upward Transformation    }}

In this we pass Person.display (husband). This sentence can be seen husband is the person type.

Converting a subclass to a parent class is moved upward above the inheritance relationship, so it is generally called upward transformation. Since the upward transformation is converted from a private type to a more general type, it is always safe and the only change that can occur is the loss of properties and methods. This is why the compiler still allows for an upward transition in situations where "no explicit transformation" or "no special tag has been specified".

Summary

With all the benefits of inheritance, is it possible to use inheritance with great fanfare? Use inheritance with caution.

First we need to be clear that inheritance has the following drawbacks:

1, the parent class changes, the subclass must change.

2, inheritance destroys the encapsulation, for the parent class, its implementation details are transparent to the subclass.

3, inheritance is a strong coupling relationship.

So when we use inheritance, we need to be sure that using inheritance is really an effective and workable approach. So do you want to use inheritance anyway? "Think in Java" provides a workaround: Ask yourself if you need to move from subclass to parent class. If you have to move up, inheritance is necessary, but if you don't, you should consider whether you need to inherit.

Java three major features--inheritance

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.