Object oriented key overview 2

Keywords: Java

9. Inherit

(1) Why use inheritance

  • Code reuse (multiple subclasses have common methods or properties)

  • Implement polymorphism (multiple subclasses override the methods of the parent class to meet their own needs)

(2) How to use inheritance

  • [access modifier] class subclass name extends parent class name{

    Subclass member variable

    Subclass member method

    }

(3) What can a subclass inherit from its parent class

  • You can inherit public and protected modified properties and methods, regardless of whether the parent and child classes are in the same package

  • You can inherit the properties and methods of the default access modifier, but the parent and child classes must be in the same class

  • Cannot inherit the constructor d of the parent class

(4) Construction in inheritance

  • Subclasses inherit all members of the parent class except the constructor, including instance properties and instance methods

  • Subclasses can add their own properties and methods to achieve the purpose of expanding themselves

  • Who defines the attribute and who initializes it, that is, in the subclass construction method, super is used to pass the initialization value of the attribute defined by the parent class to the parent class construction method, and the new attribute defined by the subclass is initialized in its own construction method.

  • Is the parent class new when subclassing new? ()

    • A: new

  • new subclass, whether the constructor of the parent class is called

    • A: Yes

  • new subclass is to call the constructor of the subclass first, and then call the constructor of the parent class

  • new subclass, execute the constructor of the parent class first, and then execute the constructor of the subclass

9.1 method override

(1) What (what is method rewriting)

  • The method name, parameter and return value type of the subclass in the inheritance relationship are the same as the method name, parameter and return value type of the parent class; the range modifier cannot be reduced; it is called method override.

(2) Why (why use method override)

  • The methods inherited from the parent class cannot meet the needs of the child class, so the child class needs to redefine the methods inherited from the parent class to meet its own needs.

(3) Where (where to use method overrides)

  • In a subclass, if the inherited method does not meet the needs, you can override the parent method.

(4) How (how to use method rewriting)

  • Redefine the inherited parent class methods that do not meet the needs.

nine 3@Override annotation

@Override is an annotation that represents the method being overridden

@Override
    public void print() {
        System.out.println("Use color printer");
    }

9.4 usage of super

super means to call a parent class member. There are two uses

(1) Call the constructor of the parent class and put it on the first line of the constructor of the child class

public Student(int age,String name){
    super(age);
    this.name = name;
}

(2) call the instance property or instance method of the parent class in the common method.

public void print(){
    super.print();
    super.name = "Xiao Wang";
}

9.5 Object class

The object class is the parent class of all classes. A class always inherits the object class directly or indirectly. Object is the highest level of the class.

public class SayHello{
    
}
public class SayHello extends Object{
    
}
//Two different expressions express the same meaning. If a class does not display the inherited Object class, it inherits the Object class by default

9.6 toString method

public class Student{
    public static void main(String[] args){
        Student s = new Student();
        //The toString method is called by default
        System.out.println(s);
        System.out.println(s.toString());
    }
}
***************************************************
//Operation results
com.xiaowei.demo0915.Student@4f3f5b24
com.xiaowei.demo0915.Student@4f3f5b24
Override toString method
public class Student {
    //Override toString method
    @Override
    public String toString(){
        return "Hello";
    }
​
    public static void main(String[] args) {
​
        Student s = new Student();
        System.out.println(s);
        System.out.println(s.toString());
    }
}
*****************************************
E:\internship\ycdl\out\production\ycdl com.xiaowei.demo0915.Student
 Hello
 Hello
​
Process finished with exit code 0

final keyword

final can modify classes, methods, and properties

  • final decorated classes cannot be inherited

  • final modified methods cannot be overridden

  • The value of the final modified attribute cannot be modified, even if it is modified to the same data as the original.

polymorphic

what is polymorphism?

Polymorphism is a variety of forms. There are two forms: the first is method overloading and the second is method rewriting.

why?

Polymorphism is to use the same method to complete different operations and reference multiple subclasses through a parent class

Where (where to use polymorphism)?

To express a method to implement multiple operations, you can use rewriting (dynamic polymorphism)

A method that returns different data can use rewriting (static polymorphism)

how?

Polymorphism can be method overloading or method rewriting

Overloads such as System.out.println() can output different types of data.

Rewriting: there are several subclasses, and there are several polymorphic rewriting methods. One method completes different operations.

The parent class reference points to the child class object (the core of polymorphism)

//The reference d1 of the parent class points to the object of the child class
Department d1 = null;
d1 = new PersonnelDept(20, "Ministry of Personnel", 5, "Responsible for recruitment", "Wang Ping", 6);
d1.printDetail();//The method of which subclass is called when the reference of the parent class points to the object of which subclass. Here, the printDetail method of the personnel department is called
        
d1 = new ResearchDept(10, "R & D department", 20, "Responsible for development", "Wang Ning", "Full stack");
d1.printDetail();//The method of which subclass is called when the reference of the parent class points to the object of which subclass. Here, the printDetail method of the R & D department is called
    
//The reference r of the subclass points to the object of the parent class
ResearchDept r =  (ResearchDept) new Department();
r.printDetail();

(1) The parent class reference points to the subclass object, which can be assigned directly

(2) A subclass reference cannot point to a parent class object unless cast, but it will cause data loss

Just like converting int type to short type in basic data type.

Upward transformation

The transformation from a child class to a parent class becomes an upward transformation

< parent type > < reference variable name > = new < child type > ();

For example: Pet pet = new Dog();

Downward transformation

The transformation from a parent class to a child class is called a downward transformation.

< subclass type > < reference variable name > = (< subclass type >) new < subclass type >);

For example: Dog dog = (Dog) new Pet();

important

The parent class reference points to the child class object. The parent class reference can only call the methods in the child class that maintain the inheritance relationship with the parent class, and cannot call the methods added by the child class.

instancesof operator

The instancesof operator is used to determine whether an object points to an instance of a class and returns true or false

for example

if(pet instanceof Dog) {
	Dog dog = (Dog) pet;
	dog.catchingFlyDisc();
}
if(pet instanceof Bird) {
	Bird bird = (Bird) pet;
	bird.fly();
}

Application of polymorphism

Examples of pet shops

Parent class: pet class

package com.kaifamiao.polymorphism;

public class Pet {
	public void toHospital() {
		System.out.println("Pet doctor");
	}
}

Subclass: Dogs

package com.kaifamiao.polymorphism;

public class Dog extends Pet {
	@Override
	public void toHospital() {
		System.out.println("Dog doctor");
	}
	public void catchingFlyDisc() {
		System.out.println("Frisbee");
	}
}

Subclass: birds

package com.kaifamiao.polymorphism;

public class Bird extends Pet {
	@Override
	public void toHospital() {
		System.out.println("Bird doctor");
	}
	
	public void fly() {
		System.out.println("flight");
	}
}

Define pet store

package com.kaifamiao.polymorphism;

import java.util.Scanner;

public class PetShop {
	/**
	 * One of the applications of polymorphism: parent class reference is used as method parameter
	 * When the parent class reference is used as a method parameter, any subclass object of the class can be passed in
	 */
	public static void test(Pet pet) {
		pet.toHospital();
		if(pet instanceof Dog) {
			((Dog)pet).catchingFlyDisc();
		}
		if(pet instanceof Bird) {
			((Bird)pet).fly();
		}
	}
	/**
	 * The second application of polymorphism: the parent class reference is used as the return value of the method
	 * When the parent class reference is used as the method return value, any child class object of the method can be returned
	 * @return
	 */
	public static Pet getPet() {
		Pet pet = null;
		Scanner s =new Scanner(System.in);
		System.out.println("Please enter the pet category to buy, 1: dog, 2: bird");
		int choice = s.nextInt();
		switch(choice) {
		case 1:
			pet = new Dog();
			break;
		case 2:
			pet = new Bird();
			break;
		default:
			System.out.println("Input error, program terminated");	
		}
		return pet;
	}
	

	public static void main(String[] args) {
		Pet pet = getPet();
		PetShop.test(pet);
	}
}

10.7.1 parent class as method parameter

public static void test(Pet pet) {

}
 One of the applications of polymorphism: parent class reference is used as method parameter
 When the parent class reference is used as a method parameter, any subclass object of the class can be passed in

10.7.2 parent class as method return value

public static Pet getPet() {

}
 The second application of polymorphism: the parent class reference is used as the return value of the method
 When the parent class reference is used as the method return value, any subclass object of the class can be returned

Posted by severndigital on Fri, 17 Sep 2021 18:06:57 -0700