08-Java inheritance, polymorphism, super keyword, final keyword

1. Inheritance

​ When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, so multiple classes do not need to define these attributes and behaviors, as long as they inherit that class.

Benefits of inheritance:

  • Code reuse
  • Code extension
  • With a relationship between classes and classes, more special types can be created.

Disadvantages of inheritance:

  • The coupling of classes is enhanced.
  • The principle of development: high cohesion, low coupling.
  • Coupling: the relationship between class and class
  • Cohesion: the ability to accomplish something by yourself

Inherited syntax format:

【修饰符】 class 子类  extends 父类{
    
    
    
}

Inherited characteristics :

  • The subclass will inherit all the non-private properties and methods of the parent class

  • The subclass will not inherit the constructor of the parent class, because the constructor of the parent class is used to create the object of the parent class

  • The constructor of the subclass must call the constructor of the parent class

    While creating the subclass object, it is used to initialize the properties inherited from the parent class. You can assign values ​​to the properties with the help of the code in the constructor of the parent class.

  • Java only supports single inheritance, multiple inheritance is not allowed, but Java supports multiple inheritance

    • A subclass can only have one "direct" parent class
    • The parent class can also have a parent class
    • A parent class can have many subclasses at the same time

1.1 keyword super

super: of the parent class

usage:

  • super.Properties

When the subclass declares a member variable with the same name as the parent class, then if you want to indicate that a member variable is of the parent class, you can add "super."

  • super.method

When the subclass overwrites the method of the parent class, and you need to call the overridden method of the parent class in the subclass, you can use "super."

  • super() or super (argument list)

super(): Indicates that the parameterless structure of the parent class is called

super (argument list): Indicates that the parameterized structure of the parent class is called

note:

(1) If you want to write super() or super (argument list), you must write it in the first line of the subclass constructor

(2) If there is no written in the constructor of the subclass: super() or super (argument list), then there will be super() by default

(3) If the parent class does not have a parameterless structure, then "must" write super (argument list) in the first line of the constructor of the subclass

(4) The traceability of super is not limited to the direct parent

The difference between this and super:

Difference this super
Access attributes Access the properties of this class, if this class does not have this property, continue to search from the parent class Direct access to attributes in the parent class
Call method Access methods in this class, if this class does not have this method, find from the parent class Direct access to methods in the parent class
Call constructor To call the constructor of this class, it must be placed in the first line of the constructor To call the parent class constructor, it must be placed in the first line of the subclass constructor
representative Represents the current object Represents the parent class

Note :

  • If "this." is used in front of a property or method, first search from this class, if not found, it will search along the parent class
  • If "super." is used in front of a property or method, then it will be searched from the direct parent class first, if not found, it will look up along the inheritance relationship
  • If there is neither "this." nor "super." in front of a property or method, follow the principle of proximity and start looking

1.2 Method rewriting

Method override (Override):

When the subclass inherits the methods of the parent class, and feel that the implementation of the method body of the parent class is not suitable for the subclass, the subclass can choose to rewrite it.

Requirements for method rewriting:

  • Method name: must be the same
  • Formal parameter list: must be the same
  • Modifier

​ Permission modifier: >=

  • Return value type

​ If the basic data type and void: must be the same

​ If it is a reference data type: <=

Note : The overridden method cannot be static, final, and invisible to subclasses

The difference between Overload and Override

Overload Rewrite
position In the same class In parent-child class
Method name Must be the same Must be the same
Form attendance table Must be different Must be the same
Return value type Irrelevant Void and basic data types must be consistent, reference data types <=
Permission modifier Irrelevant (recommended to be consistent) The permission modifier of the overridden method is either the same as the overridden method, or has a larger scope of authority than the overridden method

2.final keyword

final: final

usage:

(1) Modification class (including external class and internal class)

Indicates that this class cannot be inherited and has no subclasses

Improve safety and improve program readability.

(2) Modification method

Indicates that this method cannot be overridden

(3) Modified variables (member variables (class variables, instance variables), local variables)

It is called a constant, which means that the value of this variable cannot be modified

(4) Modify the reference data type to indicate that the address value cannot be modified.

Note: If a member variable is modified with final, it must be manually assigned, and once the value is assigned, it cannot be modified, that is, there is no set method.

3. Polymorphism

Polymorphism: Multiple manifestations of a class of things.

In java

(1) Overloading: multiple manifestations of a method function in a class

Rewrite: Parent and child classes show different forms for the same method

(2) Polymorphism of the object: If the compile-time type is inconsistent with the runtime type, polymorphism will occur (Polymorphism)

The reference of the parent class points to the object of the child class

Syntax format:

父类 引用/变量 = 子类的对象;

Polymorphic premise:

  • inherit
  • Method rewriting
  • Supertype reference points to subtype object

phenomenon:

  • Member variables: There is no polymorphism, just look at the class to which the reference variable belongs.

  • Call method in polymorphic form: look at the left/"parent class" at compile time, and look at the right/"child class" at runtime.

    When compiling, because it is compiled according to the parent class, only the methods of the parent class can be used, and the methods extended by the subclass cannot be called;

    The execution must be the method body overridden by the running subclass.

Code example:

class Person{
    
    
	public void eat(){
    
    
		System.out.println("吃饭");
	}
	public void walk(){
    
    
		System.out.println("走路");
	}
}
class Woman extends Person{
    
    
	public void eat(){
    
    
		System.out.println("细嚼慢咽的吃饭");
	}
	public void walk(){
    
    
		System.out.println("婀娜多姿走路");
	}
	public void shop(){
    
    
		System.out.println("买买买...");
	}
}
class Man extends Person{
    
    
	public void eat(){
    
    
		System.out.println("狼吞虎咽的吃饭");
	}
	public void walk(){
    
    
		System.out.println("大摇大摆的走路");
	}
	public void smoke(){
    
    
		System.out.println("吞云吐雾");
	}
}
class Test{
    
    
    public static void main(String[] args){
    
    
        Person p = new Woman();//多态引用
        p.eat();//执行子类重写
        p.walk();//执行子类重写
        //p.shop();//无法调用
    }
}

3.1 Application of polymorphism

(1) Polymorphic parameters: the formal parameter is the parent class, and the actual parameter is the subclass object

Sample code:

class Test{
    
    
    public static void main(String[] args){
    
    
        test(new Woman());//实参是子类对象
        test(new Man());//实参是子类对象
    }
    public static void test(Person p){
    
    //形参是父类类型
        p.eat();
        p.walk();
    }
}

(2) Polymorphic array: the type of the array element is the parent class, and the element stores the subclass object

Sample code: polymorphic array

class Test{
    
    
    public static void main(String[] args){
    
    
        Person[] arr = new Person[2];//多态数组
        arr[0] = new Woman();
        arr[1] = new Man();
        
        for(int i=0; i<arr.length; i++){
    
    
            all[i].eat();
            all[i].walk();
        }
    }
}

3.2 Upward and downward transition

(1) Upward transformation: automatic type conversion

When the object of the subclass is assigned to the variable of the parent class (that is, polymorphic reference), at compile time, this object is upcast to the parent class. At this time, you can't see the "specific and extended" methods of the subclass.

(2) Downward transformation: forced transformation. There is a risk. When the types are incompatible, a ClassCastException will occur when the conversion is performed. In order to avoid the occurrence of this exception, it is recommended to perform runtime type judgment before down-casting, that is, the instanceof mentioned below.

​ When you need to assign a variable of a parent class to a variable of a subclass, you need to downcast.

Run-time type transformation in order to succeed, we must ensure the preservation of the variable object type is <= strong turn

Sample code:

class Person{
    
    
	//方法代码省略...
}
class Woman extends Person{
    
    
    //方法代码省略...
}
class ChineseWoman extends Woman{
    
    
	//方法代码省略...
}
 public class Test{
    
    
     public static void main(String[] args){
    
    
		//向上转型
		Person p1 = new Woman();
		//向下转型
		Woman m = (Woman)p1; 
		//p1变量中实际存储的对象就是Woman类型,和强转的Woman类型一样

		//向上转型
		Person p2 = new ChineseWoman();
		//向下转型
		Woman w2 = (Woman) p2; 
		//p2变量中实际存储的对象是ChineseWoman类型,强制的类型是Woman,ChineseWoman<Woman类型     
     }
 }

(3)instanceof

Expression syntax format:

对象/变量  instanceof  类型

Operation result: true or false

effect:

Used to determine whether the object belongs to this type, or whether it is an object of this type or an object of this type subclass. In the development of java programs, before any downward transformation operations, instanceof must be used for judgment, and such programming habits must be developed.

Sample code:

class Person{
    
    
	//方法代码省略...
}
class Woman extends Person{
    
    
    //方法代码省略...
}
class ChineseWoman extends Woman{
    
    
	//方法代码省略...
}

 public class Test{
    
    
     public static void main(String[] args){
    
    
         Person p = new Person();
         Woman w = new Woman();
         ChineseWoman c = new ChineseWoman();
         
         if(p instanceof Woman){
    
    //false
             
         }
         if(w instanceof Woman){
    
    //true
             
         }
         if(c instanceof Woman){
    
    //true
             
         }
     }
 }

Guess you like

Origin blog.csdn.net/m0_46988935/article/details/110198397