Java Fundamentals-One of the four elements of inheritance

Source: Internet
Author: User
Tags class definition control characters export class

concept of inheritance:

Inheritance is special in its own--general relationship, that is, often said is-a relationship. The subclass inherits the parent class, indicating that the subclass is a special parent class and has some properties or methods that the parent class does not have.

Inheritance is an integral part of all OOP languages, and the extends keyword is used in Java to represent an inheritance relationship. When a class is created, it is always inherited, and it is always implicitly inherited from the root class object if it is not explicitly pointed out to inherit the class. For example, the following code:

class Person {    public person  () {             classextends person {      public Mans () {             }}

The class man inherits from the person class, so that the person class is called the parent class (the base class), and the man class is called a subclass (export Class). If an inheritance relationship exists for two classes, the subclass automatically inherits the methods and variables of the parent class, and the methods and variables of the parent class can be called in the subclass. 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.

1. Subclass inherits member variables of 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) can inherit the public and protected member variables of the parent class, cannot inherit the private member variable of the parent class, 2) for the parent class's package access member variable, if the child class and the parent class under the same package, the subclass can inherit; Subclass cannot inherit; 3) for a child class that can inherit a parent class member variable, a shadowing occurs when a member variable of the same name appears in the subclass, 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) can inherit the public and protected member methods of the parent class, cannot inherit the private member method of the parent class, 2) for the parent class's package access member method, if the child class and the parent class under the same package, the subclass can inherit; Subclass cannot inherit; 3) for a child class that can inherit a member method of a parent class, if a member method of the same name appears in the subclass, then it is called overwrite, that is, the member method of the child class overrides the Member method of the parent class with the same name. 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.

Note: Hiding and overwriting are different. Shadowing is for member variables and static methods, and overrides are for common methods. (I'll talk about it later)

3. Constructors

Subclasses are constructors that cannot inherit the parent class, but note that if the constructor of the parent class is parameterized, the constructor of the parent class must be called with the Super keyword in the constructor of the child class and be accompanied by the appropriate argument list. If the parent class has a parameterless constructor, it is not necessary to call the parent class constructor with the Super keyword in the subclass's constructor, and if the Super keyword is not used, the system automatically calls the parent class's parameterless constructor. See the following example to make it clear:

classShape {protectedString name;  PublicShape () {name= "Shape"; }          PublicShape (String name) { This. Name =name; }} classCircleextendsShape {Private Doubleradius;  PublicCircle () {radius= 0; }          PublicCircle (Doubleradius) {         This. Radius =radius; }          PublicCircle (Doubleradius,string name) {         This. Radius =radius;  This. Name =name; }}

There is no problem with this code, and if you remove the parameterless constructor of the parent class, the following code will inevitably go wrong:

Change to the following is also OK:

4.super

There are two main uses of super:

1)Super. Member variable/Super. Member method; 2)Super(Parameter1,parameter2 ...)

The first usage is primarily used to invoke a member variable or method of the same name in the subclass of the parent class;

The second is to invoke the constructor of the parent class primarily in the constructor of the subclass, and note that if it is used in the subclass constructor, it must be the first statement of the subclass constructor.

initialization order in inheritance:

From the structure of a class, there are four common patterns within it: attributes (including class attributes and instance properties), methods (including class methods and instance methods), constructors, and initialization blocks (including initialization blocks of classes and initialization blocks of instances). For the initialization order in the inheritance, it also divides into the initialization of the class and the initialization of the object.

Class initialization:

    During the preparation phase of the JVM load class, the memory space is first allocated for all class properties and class initialization blocks of the class. and initialized for it during the first initialization phase of the class, the order in which the class properties and class initialization blocks are defined determines the order in which they are initialized. If the class has a parent class, the class properties and class initialization blocks of the parent class are initialized first, beginning with the object class.

Object initialization:

    When new creates an object, it first allocates memory for object properties and initialization blocks, and performs default initialization. If there is a parent class, first allocate memory and perform initialization for the parent class object and initialization block. The    initializer in the parent class constructor is then executed before the object properties and initialization blocks of the child class are initialized.

Note:

1. During the object initialization phase, both properties and methods are for properties and methods that subclasses can inherit from the parent class, generally in the case of non-private to the parent class. Because the private adornment is unique to the parent class, the subclass does not inherit, and when the new subclass does not need to allocate space for it and perform initialization. Of course, the constructor subclass of the parent class is not inherited, but the constructor is a matter of other kinds. 2. Class initialization is performed only once, and when multiple objects are new to the same class, class properties and class initialization blocks are initialized only once.

Benefits of Inheritance

When do you define inheritance?

Inheritance is defined when a relationship exists between a class and a class. XXX is one of the yyy, XXX extends yyy
Affiliation: is a
When members of this class and local variables have the same name, this is distinguished by this.
The parent class is distinguished by super when the member variable has the same name in the child parent class.
This represents a reference to this class of objects
Super represents a space for the parent class
overriding: When the same method appears in the child parent class, the methods in the subclass are run first.
Overriding feature: Like the method name, the access modifier permission is not less than the parent class, the return type is consistent, and the argument list is consistent.
When do you use rewriting?
When you extend a subclass to a class, the subclass needs to preserve the function declaration of the parent class.
However, when you want to define the unique content of the feature in a subclass, you use the rewrite operation to complete it.
The characteristics of the constructor method in the child parent class:
When the subclass constructs the object, it is discovered that when the subclass constructor is accessed, the parent class is also running.
Cause: The first row in the subclass construction method has a default hermit statement. Super ();
Call the null argument constructor in the parent class.
Instantiation of subclasses: constructor methods in subclasses access the parameterless construction method in the parent class

Hidden in inheritance:

Hidden meaning: actually exists, but is not visible to the outside.

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 the private adornment is unique to the class and is not directly accessible in any other class; The property or method of the default adornment has the package access attribute, other classes in the same package can be accessed, and other classes in the same protected are accessible by the property or method of the same. It is also accessible in subclasses that are not in the same package, and can be accessed directly in the public-decorated properties or methods outside the class.

When a subclass inherits the parent class, the subclass can inherit the properties and methods (generally non-private adornments) in the parent class that have access control permissions, and the subclass does not inherit from the properties and methods that are unique to the private decorated parent class.

When a subclass needs to change the inherited method, it is often said to override the parent class. Once overridden, this method of the parent class behaves as hidden for the subclass. After the object of the subclass calls this method, it is called after the subclass is overridden

method, but there are two ways in which you can invoke the original method of the parent class in the subclass object:

1. Force the Subclass object type to be converted to the parent class type and make the call;

2. Call through Super.

Similarly, if a property of the same name in the parent class is defined in a subclass, the parent class property is represented as hidden in the subclass.

This and super in the inheritance:

The This in the constructor represents the object reference that is currently being initialized, and this in the method represents the object reference that is currently calling this method. This specific usage is shown in a few ways:

1. When there are multiple overloaded constructors, and one constructor needs to call another to construct it, it is called with this (Param) in its first row and only in the first row;

2. When a method in the object needs to call the other methods in this object, use this as the keynote, or do not write, in fact, the default is this as the keynote;

3. When the object property and the local variable name in the method are the same, in this method you need to explicitly use this as the keynote to represent the properties of the object, if this problem does not exist, you can not explicitly write this.

In fact, one of the problems involved is the search rule for variables: first local variables, and the variables defined in the current class, the variables that can be inherited by the quilt class defined in the parent class, and the parent class ...

Super represents calling the corresponding properties and methods in the parent class. In the method, if you need to call the method of the parent class, be sure to write it in the first line

Inheritance and Composition:

From the simple realization effect, the inheritance and the combination can achieve the same goal. and are an effective way to implement code reuse.

But in the general concept level, the two have the obvious difference.

Inheritance manifests itself as a general--special relationship, a subclass is a special parent class and a is-a relationship. The parent class has a generic attribute for all subclasses.

The combination manifests as the whole--part relation, namely has-a relation. In the composition, the "part" is extracted separately to form its own class definition, and in the "whole"

In this class definition, a section is defined as one of these properties, and through the Get and set methods, you can invoke the properties and methods in the "partial" class.

The understanding of Inheritance:

1. Inheritance is one of the three characteristics of object-oriented, and also an important means to realize code reuse. Java inheritance has the characteristics of single inheritance, with only one direct parent class per subclass.

2, Java inheritance through the extends keyword to implement, the implementation of the inherited class is called a subclass, the inherited class is called the parent class (some also known as the base class, the superclass), the parent class and the child class relationship, is a general and special relationship. Like fruit and apples, apples inherit fruit, apples are children of fruit, fruit is Apple's parent, Apple is a special kind of fruit.

3, Java uses extends as the Inheritance keyword, the extends keyword in English is the extension meaning, but is not the inheritance. Why the domestic translation of extends into succession? In addition to the historical reasons, it is also reasonable to translate extends into inheritance: The subclass extends the parent class, it will be able to get all the properties and methods of the parent class, which is very similar to the inheritance in Chinese (The offspring inherit a fortune from their fathers). It is worth noting that the subclass of Java cannot get the constructor of the parent class.

eg

classbaseclass{ Public Doubleweight;  Public voidinfo () {System.out.println ("My weight is" +weight+ "kg"); }}  Public classExtendsDemo001extendsBaseClass { Public Static voidMain (string[] args) {//Create a ExtendsDemo001 objectExtendsDemo001 Ed=NewExtendsDemo001 (); //The ExtendsDemo001 itself does not have a weight property, but the parent class of ExtendsDemo001 has a weight attribute and can also access the properties of the ExtendsDemo001 objectEd.weight= 56; //call the info () method of the ExtendsDemo001 objectEd.info (); }}

The result is: my weight is 56.0 kilograms.

Java classes can have only one parent class. This sentence is wrong, it should be said: Java class can only have a direct parent class, can have an infinite number of indirect parent class

class  Fruit  extends  plant{...}class  Apple  extends  Fruit {...}

Java Fundamentals-One of the four elements of inheritance

Related Article

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.