Inheritance in Java

Source: Internet
Author: User

As an object-oriented language, Java has three main features of object-oriented-inheritance, polymorphism, encapsulation.

Inherit as the name implies, succession, undertake, inherit the meaning. An object-oriented language has the advantage of being able to use examples in life to illustrate object-oriented features. So let's take a look at the inheritance relationships in life. Most common: parents and children; automobiles, electric cars, bicycles and cars. No matter what kind of car, have the characteristics of the car. Again say: home noodles of rice cooker, induction cooker, refrigerator. They all belong to the electric class, all have the name this attribute, also all need electricity this method. Wouldn't it be a waste of time and energy if we were going to write all these repetitive codes in the program? By contacting the prior knowledge, we can abstract a class from an object. Then we should be able to abstract a class with a common property and method from a class with a containing relationship, that is, the parent class. For example, whether it is a triangle, a rectangle or a circle, they have the method of seeking the edge length, then you can abstract a parent class, there is a way to find the edge length. Inheritance in Java uses the extends keyword, where the inherited class is called a subclass (derived or superclass), and the inherited class is called the parent class (or base Class). Any class that can have an inclusive relationship can implement an inheritance relationship.

The following are the inherited formats:

 Public class extends parent class Name {}

Consider a simple example of inheritance:

//Parent Class Public classPerson {PrivateString name;  Public intAge ; protected Charsex;        String Country;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. name=name; }         Public voidspeak () {System.out.println (name+ "Talking now! "); }}//sub-class Public classTeacherextendsPerson {}//Test Class Public classTest { Public Static voidMain (String args[]) {Teacher T=NewTeacher ();//instantiating subclasses//t.name= "Zhang San";//Compiler ErrorT.sex= ' man '; T.age=10; T.country= "China"; T.setname ("Zhang San");        T.getname ();    T.speak (); }}

After running the discovery can output normally, that is, in the subclass without defining any properties and methods, you can use the property and methods inherited by the parent class, which also illustrates the implementation of the inheritance. So what does the subclass inherit from the parent class? The answer is that the subclass class can inherit all the properties and methods of the parent class. There may be people wondering, is the name attribute in the test class not an error? So is the private property not able to be inherited? If the subclass does not inherit the name attribute of the parent class, then the name attribute does not exist in the child class. Since there is no, then the subclass of SetName, GetName, speak these three methods should be error, but the fact is that there is no error, so the Java neutron class can inherit all the methods and property values in the parent class. Access modifiers in Java are used to restrict access to properties or methods in a class, and are not directly related to whether they are inherited or not. This is why the Name property value is an error.

Of course, subclasses can define their own properties and methods, and this does not have any problems. After figuring out what subclasses can inherit from the parent class, we add this piece of code to the parent class:

 Public Person (String name) {    this. name=name;} 

After adding this constructor to the parent class, it is found that the sub-class error! What is this for? The original Java when instantiating the subclass object will be called through the subclass of the parameterless constructor of the parent class of the parameterless constructor, when the parent class is provided with a parameter constructor, the JVM will no longer provide a default parameterless constructor for the parent class, the subclass instantiation object cannot find the parent class no parameter constructor compiler will naturally error. Let's take a look at the following:

Add a parameterless constructor to the parent class:

 Public Person () {     System.out.println ("The parent class constructor is called");}

The console output results are as follows:

This also proves that the subclass invokes the parameterless constructor of the parent class, that is, when the subclass is instantiated, it produces two objects (this is not considered object), a subclass object, and a parent class object.

It's good to believe that the reader's inheritance of the class is basically clear. We return to the example we have just used, and we define the human class, which has a method of speaking (speak) in the class. Try to define several classes: Chinese, American, Russian, all of them. This class has a way of speaking, but do they speak the same way? Can I use the parent class's speaking methods directly? Chinese people speak Chinese, Americans in English, Russian in Russian, obviously can't use the same method. So what if the parent's method doesn't meet the requirements of the subclass? Here you can use the rewrite of the method.

Let's take a look at the condition of the method override: 1. Must have an inheritance relationship; 2. When overriding a method, the access modifier for the subclass method must be greater than or equal to the access modifier of the parent class method, and 3. The return value type, method name, and parameter of the subclass method must be consistent with the parent class when overriding the method

Satisfying these conditions is called the rewrite of the method. See Example:

  publicclassextends  person{    public  Viod speak () {        System.out.println (name+ "Chinese Speaking is Chinese, the way of speaking is different.") ");    }}

This completes the rewrite of the method, instantiates the Chinese object in the test class, and invokes the Speak method to output: XXX is Chinese speaking Chinese, the way of speaking is different. It is important to note that after a method has been overridden, the speak method that is called with the subclass object is a subclass of the overridden method, and no longer the parent class's method. The invocation of a method depends on the class that follows the new keyword, and if it is a parent class, the method that calls the parent class, and, if it is a subclass, the overridden method of the subclass. If you still want to invoke the method of the parent class, you can use the Super keyword to make the call. Change the code to the following:

 Public class extends person{    public  Viod speak () {        Super. Speak ();        SYSTEM.OUT.PRINTLN (name+ "Chinese Speaking is Chinese, the way of speaking is different.") ");    }}

This will output two words: xxx is talking

XXX is Chinese speaking Chinese, the way of speaking is different.

It is important to note that the difference between overriding and overloading is primarily conditional:

Rewrite: The above conditions have been listed, here is not to repeat. An important use of overrides is to extend the methods of the parent class to meet the subclasses ' own needs.

Overloading: The condition is: 1. A class of similar or inherited relationships; 2. The method name is the same, but the parameters of the method must be different. Overloading of methods is important to handle different types of data.

Another advantage of inheriting classes is the automatic transformation of--java. In Java, an automatic transformation occurs when a small range of data is converted to a wide range of data. The advantage of automatic transformation is that I can define a method in a class, the parameter of the method is the parent class type, so no matter how many subclasses, it can call this method, which greatly improves the program's extensibility. For example, we have been using this example, if there is an extraterrestrial visitor, to teach humans a very good technology, if there are only one or two kinds of people, that can be in the Aliens class to write two teaching methods, but if there are 100 kinds of 1000 kinds of people? Can't you write 1000 different ways? Then you can use the following method:

 Public class alien{    publicvoid  teach (person p) {        p.study ();}    }

So no matter how many kinds of people, we can go directly into different sub-class objects, through automatic transformation to call their own learning methods, so it is not flattered. Of course, there will be problems, if the use of automatic transformation calls subclass-specific methods will be an error, but this is the Java compiler mechanism generated by the problem, automatic transformation has its advantages, we need to avoid weaknesses in the good.

Summary: Classes that contain relationships can use inheritance, subclasses can inherit all the properties and methods of the parent class, and inheritance can improve the reusability of code and the extension of the program. Rewriting can extend the way of the parent class, better adapt to the needs of subclasses, the automatic transformation of Java can be a lot of simplification of code, but there are problems (of course, does not affect our use).

Inheritance in Java

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.