Inheritance of Java Basics

Source: Internet
Author: User
Tags modifier

In "Think in Java" There is a sentence: Reuse code is one of Java's many compelling features. But to be a revolutionary language, it's not enough to just copy the code and change it, and it has to be able to do more. The most noticeable in this sentence is the "Reuse code", as much as possible to reuse the code that we programmers have been pursuing, and now I introduce a way to reuse code, is one of Java three major features---inheritance.

Inherited

Let's take a look at an example of the previous blog post (the Java Enhancement-----The encapsulation of three major features of Java).

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 understand the concept of inheritance, inheritance is to use the definition of existing classes as the basis for the creation of new classes of technology, the definition of new classes can add new data or new functions, but also with the function of the parent class, but can not selectively inherit the parent class. By using inheritance, we can easily reuse the previous code, which can greatly improve the efficiency of development.

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 "is-a" relationship, if there are two objects A and B, if it can be described as "A is B", it can be said that a inherits B, where B is the successor called the parent class or superclass, A is the successor called the subclass or 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.

Admittedly, inheritance defines how classes relate to each other and share attributes. For several of the same or known classes, we can abstract out their common behavior or zodiac 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, methods, 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.

Admittedly, there must be three things to be said 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, it is important to initialize the constructor correctly, and only if there is only one way 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.

public class Person {    protected String name;    protected int age;    protected String sex;        Person () {        System.out.println (' person constrctor ... ');}    } public class Husband extends person{    private Wife Wife;    Husband () {        System.out.println ("Husband Constructor ...");    }        public static void Main (string[] args) {        Husband Husband  = new Husband ();}    } Output:person Constrctor ... Husband Constructor ...

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.

public class Person {    protected String name;    protected int age;    protected String sex;        Person (String name) {        System.out.println ("Person constrctor-----" + name);}    } public class Husband extends person{    private Wife Wife;    Husband () {        super ("Chenssy");        System.out.println ("Husband Constructor ...");        public static void Main (string[] args) {        Husband Husband  = new Husband ();}    } Output:person constrctor-----Chenssyhusband Constructor ...

So in summary: for inheritance, subclasses call the constructor of the parent class by default, but if there is no default parent class constructor, 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, it indicates that he is private to the class user, but is accessible to any subclass that inherits from this class, or any other class that is in the same package.

public class Person {    private String name;    private int age;    Private String sex;    Protected String GetName () {        return name;    }    protected void SetName (String name) {        this.name = name;    }    Public String toString () {        return ' this name is ' + name;    }        /** omit other setter, getter method **/}public class Husband extends person{    private Wife Wife;    Public  String toString () {        setName ("Chenssy");    Call the parent class's SetName ();        return  super.tostring ();    Call the ToString () method of the parent class    } public    static void Main (string[] args) {        Husband Husband = new Husband ();                System.out.println (Husband.tostring ());}    } Output:this name is Chenssy

From the example above you can read a book subclass husband can obviously call SetName () of the parent class person.

Admittedly, although you can use the protected access modifier to restrict access to the properties and methods of the parent class, the best way to do this is to keep the property private (we should keep changing the underlying implementation consistently) and control the access rights of the class's inheritors through the protected method.

Upward transformation

In the above inheritance we talked about the is-a of inheritance is the relationship between cats and 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:

public class Person {public    void display () {        System.out.println ("Play person ...");        static void display (person person) {        person.display ();}    } public class Husband extends person{public    static void Main (string[] args) {        Husband Husband = new Husband (); 
   
    person.display (husband);      Transition Up    }}
   

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 upward transformation in cases where "the transformation has not been explicitly expressed" and "no special tags have been specified".

Careful inheritance

With all the benefits of inheritance, is it possible to use inheritance with great fanfare? Give you a word: be careful with inheritance.

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.

using inheritance!!!!!!!!!!!!!!!!!!!!!!!!!!! with caution

Transfer from https://www.cnblogs.com/chenssy/p/3354884.html

Inheritance of Java Basics

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.