Knowledge point: java inheritance and polymorphism

java-inheritance and polymorphism

inherit

Inheritance:
1. Inheritance is one of the three major features of object-oriented programming. It is a mechanism for creating new classes based on existing classes. The class derived from inheritance is calledSubclass(Or derived class), the inherited class is calledfather(Or superclass).
2. Only one parent class is allowed for each class in Java. The syntax is as follows:
class <child class> extends <parent class>
3.Object classIs the direct parent or indirect parent of all classes.

Note: 1. The final modified class cannot have subclasses.
2. When private modify the method or attribute in the parent class, the subclass can no longer inherit the method or attribute.
3. Existing classes in Java (such as Void, String, Class, Scanner, System, 8 basic data types corresponding to packaging classes (Short, Integer, Long, Float, Double, Byte, Character)) have been final modified , So these classesCannot be inherited

The role of inheritance: subclasses can inherit certain member variables and methods in the parent class, which improves code reuse, and subclasses can also add new member variables and methods

this keyword: used to call the constructor in this class (this () calls the parameterless constructor; this (parameter) calls the parameterized constructor)
super keyword: used to call the constructor in the parent class (super () ; Call the parameterless construction method, super (parameter); call the parameterized construction method)

The influence of the
parent class on the construction method of the child class: the parent class:

package Test;

public class Person {

	public Person() {
		System.out.println("父类无参构造方法");
	}
	
	public Person(int age) {
		System.out.println("父类有参构造方法");
	}
}

Subclass:

package Test;

public class Student extends Person{
	
	public Student() {
		super();//可省
		//无this存在时,此处默认有个super()来调用父类无参构造方法
		System.out.println("子类无参构造方法");
	}
	
	public Student(String name) {
		this();
		//有this存在时,则默认的super()消失,此处this()调用上面的无参构造方法
		System.out.println("子类有参构造方法");
	}
	
	public static void main(String[] args) {
		new Student();//调用Student类中的无参构造方法
		Student stu = new Student("a");//调用Student类中的有参构造方法
	}
}

result:

父类无参构造方法
子类无参构造方法
父类无参构造方法
子类无参构造方法
子类有参构造方法

In a word: the subclass parameterless constructor must call the parent class constructor (with or without parameters), and the subclass parameterless constructor must call the parent class constructor without this.

The parent class member variable is overwritten
1. When the subclass member variable and the parent class member variable have the same name, for the subclass object, the parent class member variable cannot be inherited by the subclass (ie, the subclass member variable overwrites the parent class member Variables), at this time the member variables of the subclass hide the member variables of the parent class.
2. If you want to use the hidden parent class member variable in the non-statically modified code block or method of the subclass, you can achieve it through the super keyword (super . Attribute name).

Rewrite

Rewrite is an important point inherited knowledge of
rewriting: that in order to more accurately describe subclass object dictation feature, you need to be rewritten methods inherited that modify the method inherited from the parent class, so that this method is more accurate Describe the characteristics of the subclass.
An @Override annotation can be added before the modified method , and such annotations can also let us know whether this method is modified. (Non-overriding methods with this comment will report errors)

If you want to call the overridden method of the parent class in the non-statically modified code block or method of the subclass, you can achieve it through the super keyword: the
Insert picture description here
Insert picture description here
rewriting needs to meet the following conditions:
1. The subclass rewriting method and the parent class are overridden The method of the method is the same in the method name and parameter list;
2. If the method of the parent class is overwritten does not have a return value type or the return value type is a basic data type, the return value type of the method that requires the subclass to be overridden and the parent class are repeated The return type of the write method is the same;
3. If the return type of the overridden method of the parent class is a reference data type, the return type of the method that requires the subclass to rewrite is the same as the return type of the overridden method of the parent class Or its subclass.
Insert picture description here
String is a subclass of Object, it is also rewritten.
Insert picture description here
4. The subclass rewriting method cannot narrow the access permission of the parent class rewritten method, the subclass rewriting method access permission must be greater than or equal to the parent class rewritten method access permission: the
Insert picture description here
subclass rewriting method access permission is less than The access permission of the overridden method of the parent class is reported as error
Insert picture description here
5. The static method in the parent class can be inherited by the subclass, but it cannot be overridden by the
subclass.

Insert picture description here
Due to the static modification, it cannot be rewritten.
Insert picture description here

The influence of parent class construction method on subclass construction method

1. If no constructor is defined in a class, there is a parameterless constructor by default, whose structure is as follows:
public class name () {
 super (); // must be placed on the first line of valid code to call the parent class No parameter constructor
}
2, this ([parameter list]) calls this class constructor, but it must be placed on the first line of valid code; so if a constructor has called this class constructor, you can no longer call the parent class constructor method.
3. If the subclass constructor does not call this class constructor, nor does it specify to call the parent class constructor, the parent class no-parameter constructor is called by default.

package 父类构造方法对子类构造方法的影响;

public class Father {

	public Father() {
		super();//调用Object类构造方法
		System.out.println("父类构造方法");
	}

}
package 父类构造方法对子类构造方法的影响;

public class Son extends Father{

	public Son() {
		super();
		System.out.println("子类构造方法");
	}
	

}

Result: The parent class constructor is called through the subclass

父类构造方法
子类构造方法

4. Summary:
   a. If the parent class has a parameterless construction method (whether explicit or implicit) and the construction method in the subclass does not explicitly specify which construction method of the parent class is called, the subclass does not call this The constructors of the other constructors of the subclass all use super () to implicitly call the parameterless constructor of the
   parent class b. If the parent class does not have a parameterless constructor (whether explicit or implicit), the subclass constructor is required Must directly or indirectly specify the calling method of the parent class or this class

Keyword final summary

1. The modified variable is a constant;
2. The modified method cannot be rewritten;
3. The modified class has no subclasses ( String , the packaging class corresponding to the eight basic data types: byte-Byte, short-Short, int-Integer , Char-Character ... )

Keyword supper summary

1. The super keyword can call member variables (super. Attributes) and methods (super. Parent class methods ([parameter list])) of the parent class.
2. The super keyword can be used in the subclass constructor to call the superclass constructor: super ([parameter list]);
3. super cannot be used in static methods or static code blocks.

Polymorphism

Polymorphism is: a method exists in multiple states, and
its principle is similar to automatic type data conversion:

int a=12;
long b=a;//int类型自动转换为long

Polymorphism : first create an object of the subclass, and then assign the object created by the subclass to a variable of the parent class (passage of address), and the subclass rewrites a method in the parent classCompile timeAlthough the method called is the parent method, but inOperation phaseThis variable will point to the object created by the subclass, so the final call is the method in the subclass. One method has multiple states, that is, polymorphism.
Note : 1. When the method of the parent class is not rewritten in the child class, there is no polymorphism when calling this method.
2. Polymorphism is only reflected in the method, not in the attribute, for example:
Insert picture description here
the move method of both are subclasses, but the name attribute is different! The name of the subclass object is of the subclass, and the name of the parent class object is of the superclass.

father:

package com.zzu;

public class Mammal {
	
	public void move() {
		System.out.println("正在游动。。。");
	}

}

Subclass:

package com.zzu;

public class Whale extends Mammal{
	
	double weight=1;
	
	public void move() {
		System.out.println("靠鳍游动。。。");
	}
	
	public void eat() {
		System.out.println("正在吃东西......");
	}

}

run:

package com.zzu;

public class Ocean {
	
	public static void main(String[] args) {
		Whale whale = new Whale();
		whale.move();//直接调用子类方法
		
		//多态
		Mammal mammal = whale;     //上转型   
		//等价于Mammal mammal = new Whale();
		mammal.move();     //表面上是父类方法,实际上是子类的方法
		
		//System.out.println(mammal.weight); 
		//mammal.eat();    //上转型对象是不能调用子类中新增方法和属性的!这两种均为错误!
		
		//证明传递的是地址:
		System.out.println(mammal);
		System.out.println(whale);//最终结果二者相同,说明二者的地址是相同的
		
		//int c = (int)b;    //强制数据类型转换
		Whale mammal2 = (Whale)mammal;      //下转型,将大类型强制转换为小类型,并将其赋值给小类型。
		mammal2.eat();
		System.out.println(mammal2.weight);//此时就可以用子类新增的属性和方法

		
		//Whale whale2 = (Whale)new Mammal();此为写法会报错
		//只有上转型过的对象才可以进行下转型!!!
	}
}

The running result is:

靠鳍游动。。。
靠鳍游动。。。
com.zzu.Whale@52e922
com.zzu.Whale@52e922
正在吃东西......
1.0
	多态特点:
	1、编译时和运行时类型不一致
	2、编译时调用的方法一定被子类所重写
	3、父类类型的变量 = 子类类型的对象(上转型对象)

Upper transition object

Subclass objects instantiated parent class assigned to the variable declaration, the object is called an object on the transformation, a process known as transformation on the object, corresponds to the data type conversion of automatic type conversions:
Insert picture description here
Insert picture description here
cast to the type of mammal to Mammal Whale Type
Insert picture description here
Notes:
1. The newly transformed object cannot manipulate the newly added member variables of the subclass; it cannot call the newly added methods of the subclass: an
Insert picture description here
Insert picture description here
error will occur when the newly transformed object calls the newly added property or method of the subclass
Insert picture description here
2. The upcast object calls the parent class method If the method has been overridden by a subclass, the behavior characteristics of the subclass after overwriting will be displayed; otherwise, the behavior characteristics of the parent class will be displayed.
3. Use the upper transformation object to call the global variable of the parent class , regardless of whether the global variable has been overwritten by the subclass, the global variable in the parent class is used:
Insert picture description here

Under transformation

1. The upper transformation object can be forced to be converted into an object of the subclass type that created the object, that is, the upper transformation object is restored to a subclass object, called the lower transformation object . (Implemented by forced conversion)
2. The restored object has all the properties and functions of the subclass, that is, it can operate the member variables inherited or added in the subclass, and can call the inherited or new methods in the subclass.
Insert picture description here
Note: It is not possible to assign objects created by a parent class to variables declared by a child class through coercion. ( That is, only the objects after the transformation can be transformed )

to sum up:

1. Polymorphism must be inherited;
polymorphism must be rewritten;
polymorphic compile-time type and runtime type must be different.
(Polymorphism is only reflected in the method)
2. The object created by the subclass is assigned to a variable of the parent type, which is called the upper transformation object
3. The upper transformation object cannot call the newly added subclass (the subclass is different from the parent class) ) Methods and properties.
4. The object created by the parent class is assigned to a variable of the subclass type after forced conversion, which is called the lower transformation object (but only when this object has undergone the upper transformation, the lower transformation can be performed).

Published 30 original articles · won 33 · views 1288

Guess you like

Origin blog.csdn.net/weixin_45949075/article/details/103330695