Java 0 Basic Starter Series Day13 Java class inheritance and polymorphism

Source: Internet
Author: User
Tags control characters export class

Inheritance is a very important feature of the class, what? You don't even know how to inherit? Are you trying to kill your dad to inherit dad's legacy? Funny

A joke, the inheritance here and our real life is still very different from the inheritance, a class can inherit another class, the inherited content includes properties and methods, the inherited class is called the parent class or the base class, the inherited class is called the subclass or the export class, in the subclass can call the parent class's methods and variables. In Java, only single inheritance is allowed, that is, a class can only be displayed to inherit from a parent class at most. But a class can be inherited by multiple classes, which means that a class can have more than one subclass. This is the equivalent of a person cannot have more than one father (funny, Lao Wang is not satisfied).

Talk not much, first look at chestnuts:

 Public classEmployee {PrivateString name;//namePrivate Doublesalary;//Salary
constructor function PublicEmployee (String name,intAgeDoublesalary) { This. Name =name; This. Age =Age ; This. Salary =salary; } PublicString GetName () {returnname; } Public Doublegetsalary () {returnsalary; } Public intGetage () {returnAge ; }}

We define an employee class (employee Class), define some simple member variables and methods, and then define a manager class to inherit from this class.

 Public classManagerextendsemployee{Private Doublebonus;//Bonuses

Constructors PublicManager (String name,Doublesalary) { Super(name,salary); Bonus= 0; }
Set Bonus Public voidSetbonus (Doublebonus) { This. Bonus =bonus; }//Overloads the Getsalary method of the parent class @Override Public Doublegetsalary () {DoubleBasesalary =Super. Getsalary (); returnBasesalary +bonus; }}

What needs to be described here is the use of super and this, super is the parent class reference, you can use it to invoke the parent class's methods and properties, you can think of it as the parent class to communicate with the sub-class bridge, and this is a self-reference, you can invoke its own properties and methods, in the constructor we used the Super (Name,salary); This invokes the constructor of the parent class,

Why can the manager inherit the employee class? Because there is a is-a relationship between them, the manager is also an employee, there are many attributes such as name, salary, and method, such as name and salary, but it also has its own unique properties and methods, and can overload the parent class, such as the getsalary above. The manager class object here inherits the method of the parent employee, so the manager object can use the GetName () method directly, overloading the Getsalary method, so when invoking the method of the manager object, The Getsalary method of the subclass is called, not the parent class,

What kind of information can you inherit from the parent class?

1. Subclasses can inherit member variables of the parent class

When a subclass inherits a class, the member variables in the parent class can be used, but not all member variables of the parent class are fully inherited. The specific principles are as follows:

1) The ability to inherit the public and protected member variables of the parent class, and the private member variables of the parent class cannot be inherited;

2) for the package access member variable of the parent class, the subclass can inherit if the child class and parent class are under the same package, otherwise the subclass cannot inherit;

3) for the parent class member variable that the subclass can inherit, if a member variable of the same name appears in the subclass, a shadowing occurs, that is, the member variable of the child class masks the member variable with the same name as the parent class. If you want to access a member variable of the same name in the parent class in a subclass, you need to use the Super keyword to refer to it.

2. Subclasses inherit methods of parent class

Similarly, subclasses do not fully inherit all the methods of the parent class.

1) The ability to inherit the public and protected member methods of the parent class, and the private member method of the parent class cannot be inherited;

2) for the parent class of the package access member method, if the child class and the parent class under the same package, the subclass can inherit, otherwise, the subclass can not inherit;

3) for the parent class member method that the subclass can inherit, if a member method of the same name appears in the subclass, then it is called overwrite, that is, the member method of the subclass overrides the member method with the same name as the parent class. If you want to access a member method of the same name in the parent class in a subclass, you need to use the Super keyword to refer to it.

Here said many times public,private and protected, about the access rights do not seem to have a formal introduction, here, by the way briefly introduced:

The Java class has three access controls: private, protected, and public, and is represented as a default access control state when the three access control characters are not written. Therefore, there are four levels of access control altogether.

The specific access control performance is as follows:

The property or method of private modification is unique to the class and cannot be accessed directly in any other class;

The property or method of the default adornment has a package access attribute, and other classes in the same package can be accessed;

Protected-Modified properties or methods can be accessed in other classes in the same class, and also in subclasses that are not in the same package;

Public-decorated properties or methods can be accessed directly in the outer class.

Why should we introduce the concept of access rights? Of course, in order to better package, just like making a machine, naturally want to put all the wires are hidden in the box instead of the swagger hanging outside being spit groove, and this is more secure, only to the user or user programmers to see what they want to see the content is good, the others are hidden.

Although the subclass manager does not inherit the name and salary attributes of the parent employee, but does not mean that the operation of the two properties is meaningless, it can be understood that a subclass object contains a parent class object, for example, as if we had assembled several different computers, For the sake of convenience can choose the same host box, which is configured with the same power and fans, and other configuration of each computer can be different, even if necessary, some computers can also change the fan and power, although the final performance may be a far cry, but from the appearance of the look, they are similar. (Of course, if you have to modify the completely different is also possible) the configuration of the fan and the power of the host box is equivalent to our parent class, and different computers are the equivalent of subclasses, subclasses can call the parent class of public methods, such as turning the fan, but not directly change the host box color, because the parent class does not provide such a permission But this does not mean that the host box color is not used for subclasses, it is still part of the subclass, just can't manipulate it directly.

The contents of the access rights are introduced here, now return to our inheritance, the following is a chestnut using the manager class:

 Public classManagertest { Public Static voidMain (string[] args) {Manager boss=NewManager ("Frank", 100000);//define a Manager variable Boss.setbonus (10000);//Set bonus employee[] staff=NewEmployee[3];//Creating an employee array
Assigning a value to an array staff[0] =boss; staff[1] =NewEmployee ("Alan", 8000); staff[2] =NewEmployee ("Tom", 9000); Traversing an output array element for(Employee e:staff) System.out.println ("Name:" +e.getname () + "Salary:" +e.getsalary ()); }}

Here we define an employee array and assign a manager variable to the first element of the employee array, and you may be wondering, not saying that you can only use assignment between variables of the same type? This is true, but because the manager class is a subclass of employee, a manager object has all the attributes and methods of the employee, that is, what the employee can do, and it can do the same, so Assigning the variables of the manager class to the employee variable is not a problem, but vice versa, because the manager class has its own method Setbonus (), and employee is not able to implement it. When we traverse the output, we use all the elements as employee objects, and the output is as follows:

Name:frank salary:110000.0Name:alan Salary:8000.0name:tom Salary:9000.0

Our boss variable, when calling the Getsalary method, is obviously called the subclass method, the basic salary is added to the bonus before the return.

So, why do you have to use inheritance?

The reason is very simple, one is can implement code reuse, like this example, employee's GetName method Quilt Manager reuse, manager can directly use this method, this can save a lot of code.

Secondly, you can achieve polymorphism, say you may not believe, we just chestnut has been used to a very great concept-polymorphic, when traversing the output, a parent object reference to the child class object, and called the subclass method.

So what are the benefits of doing this? What is the meaning of polymorphism?

Simple, convenient, continue to use our chestnut just now, if we have a personnel management class, personnelmanagement, need to input the information of employees, there is a record method, if we use polymorphic characteristics, Just pass in an employee object to the record method, whether the manager or the ordinary employee can use the same way to deal with, otherwise we need to design a method for the manager and employees, it may feel fine, but if there are many other positions, such as General manager, Deputy Manager, Manager Assistant, HR manager, purchasing Manager, can you design a method for each position at this time? Obviously unrealistic, and this loses scalability and flexibility, turning an art activity into a physical activity that will deprive you of the pleasure of programming.

Therefore, inheritance and polymorphism is also very simple, inheritance is to use extends to inherit the parent class property and methods, polymorphism is the child class object can be considered as the parent object for uniform processing, in order to achieve and increase the code reusability, so that your code is more and more coquettish.

This class of inheritance and polymorphism is explained, welcome to continue to pay attention! Like my tutorial words remember to move small hands under the recommendation, also welcome to follow my blog.

Java 0 Basic Starter Series Day13 Java class inheritance and polymorphism

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.