JAVA object oriented

1. Basic concepts of inheritance

Inheritance is one of the three object-oriented features. Inheritance is everywhere. Inheritance is not only code reuse, but also the essence is to write code with abstract thinking in order to achieve stronger scalability of the program

Inheritance is the process of creating a new class from an existing class
Inheritance is one of the three characteristics of object - oriented
The inherited class is called the parent class (superclass), and the class that inherits the father is called the child class (derived class)
Inheritance means that one object directly uses the properties and methods of another object
Code reuse can be achieved through inheritance

Protected (protected access modifier, used to modify properties and methods. Properties and methods modified with protected can be inherited by subclasses)

2. Restrictions on Succession

Restrictions on inheritance:
java can only implement single inheritance, that is, a class can only have one parent class
Multi level inheritance is allowed, that is, a subclass can have a parent class, and a parent class can also have other parents
Inheritance can only inherit non private properties and methods
Constructor cannot be inherited

When creating a subclass object, the constructor of the parent class will also be called. Why?

Because the subclass needs to use the data of the parent class, it needs to initialize the data through the construction method of the parent class
If the default constructor is used when creating a subclass object, the default constructor of the parent class will also be called
//If the default constructor is used when creating a subclass object, the default constructor of the parent class will also be called
If you create a subclass object, the default constructor of the parent class will be called

Inheritance summary

Inheritance occurs between multiple classes
Inherit using the keyword extends
JAVA can only inherit in single layer, and multi-layer inheritance is allowed
The inherited class is called the parent class (superclass), and the class that inherits the parent class is called the subclass (derived class)
Non private properties and methods in the parent class can be inherited by subclasses
Protected (protected access modifier). The modified property or method can be inherited by subclasses
Constructor cannot be inherited
Creating an object will call the construction method. Calling the construction method does not necessarily create this kind of object
Instantiating a subclass object will first call the construction method of the parent class. If there is no default construction method in the parent class, the subclass must call the parameterized construction method of the parent class through super(...), and super can only be in the first sentence of the subclass construction method

Benefits of inheritance

Improve code reusability
Improve code maintainability
Making the relationship between classes is the premise of polymorphism

Disadvantages of inheritance

Enhanced coupling between classes

Development principle, high cohesion, low coupling

/**
	2022-2-20
	Inheritance: inheritance is the process of creating a new class from an existing class
	Inheriting a parent class can only inherit non private data (properties and methods)
	protected Access permission modifier, which is used in inheritance relationship. Properties or methods modified with protected in parent class can be inherited by subclasses
	
*/
public class Test34{
	public static void main(String[] args){
		
		HomeDog hd=new HomeDog();
		hd.print();
		
		System.out.println("---------------------------------");
		HomeDog homedog=new HomeDog("Wangcai");
		homedog.print();
		homedog.eat();//Improve code reusability
		
		System.out.println("---------------------------------");
		HuskDog huskdog=new HuskDog("Siberian Husky","male");
		huskdog.show();
	}
}

class Dog{
	
	protected String name;
	protected String sex;
	
	public Dog(){
		System.out.println("I am Dog Default construction method for!");
	}
	
	public Dog(String name,String sex){
		this.name=name;
		this.sex=sex;
		System.out.println("I am Dog Parametric construction method of!");
	}
	
	//Improve code maintainability
	public void eat(){
		System.out.println("having dinner!");
	}
}

class HomeDog extends Dog{
	
	public HomeDog(){
		super();
		System.out.println("I am HomeDog Default construction method for!");
	}
	
	public HomeDog(String name){
		this.name=name;
		System.out.println("HomeDog The construction method with parameters is executed!");
	}
	
	public void print(){
		System.out.println("I am a domestic dog!");
	}
}

class HuskDog extends Dog{
	
	public HuskDog(){
		super();
		System.out.println("I am HuskDog Default construction method for!");
	}
	
	public HuskDog(String name,String sex){
		super(name,sex);//Only in the first sentence
		System.out.println("I am HuskDog Parametric construction method of!");
	}
	
	public void show(){
		System.out.println("I'm a husky,I can tear down the house!");
	}
}

3. Instantiation process of subclasses

When a subclass instantiates, it will first let its parent class instantiate, and then the subclass instantiates itself

Instantiation of subclasses:
When a subclass is instantiated, the constructor of the parent class will be called first
If there is no default constructor in the parent class, the constructor of the child class must call the constructor of the parent class

Conclusion:
The constructor is only used to initialize the fields in the class and execute some initialization code
Calling a constructor does not generate an object

4. Method rewriting

The difference between interview question rewriting and overloading is that method rewriting occurs in the inheritance relationship between child and parent classes, which is different from method overloading in the same class

Overriding method

In JAVA, subclasses can inherit the methods in the parent class without rewriting the same methods However, sometimes subclasses do not want to inherit the methods of the parent class, but want to make certain modifications, which requires method rewriting Method overrides are also called method overrides
In the subclass and parent class, after overriding the method, the method will be called according to the object type created

Some features of method Rewriting:
Occurs in the child parent class. The return value, method name and parameter list of the two methods overridden by the method must be exactly the same (the child class overrides the method of the parent class)
The exception thrown by the subclass cannot exceed the exception thrown by the corresponding method of the parent class (the subclass exception cannot be greater than the parent exception)
The access level of the subclass method cannot be lower than that of the corresponding method of the parent class (the access level of the subclass cannot be lower than that of the parent class)
If the method in the parent class is modified with any modifiers such as private, static and final, it cannot be overridden by the child class

Why rewrite methods? Or what is the purpose of method rewriting?

If the method inherited by the subclass from the parent class cannot meet the specific needs of the subclass, the subclass needs the corresponding method in the parent class, and the rewriting of the method is also the embodiment of program extension

Interview question: what is the difference between overloading and overriding?

Overloading: method overloading occurs in the same class. The method name is the same, the parameter list is different, and the return value is irrelevant
Overriding: Method overriding occurs in the child and parent classes. The method name is the same, the parameter list is the same, and the return value is the same. The access modifier of the child class must be greater than or equal to the access modifier of the parent class. The exception declaration of the child class must be less than or equal to the exception declaration of the parent class. If the method is modified by private, static, and final, it cannot be overridden

5.super keyword

super can complete the following operations:
Using super to call properties in the parent class, you can get information from the parent class instance
Using super to call the method in the parent class, you can delegate the parent object to help complete something
When using super to call the constructor in the parent class (in the form of super (argument)), you must call the corresponding constructor in the parent class in the first statement of the constructor in the subclass. If it is not displayed, it will call the parameterless constructor of the parent class by default, such as super();

/**
	2022-2-20
	Inheritance: inheritance is the process of creating a new class from an existing class
	Inheriting a parent class can only inherit non private data (properties and methods)
	protected Access permission modifier, which is used in inheritance relationship. Properties or methods modified with protected in parent class can be inherited by subclasses
	
*/
public class Test34{
	public static void main(String[] args){
		
		HomeDog hd=new HomeDog();
		hd.print();
		
		System.out.println("---------------------------------");
		HomeDog homedog=new HomeDog("Wangcai");
		homedog.print();
		homedog.eat();//Improve code reusability
		
		
		System.out.println("---------------------------------");
		HuskDog huskdog=new HuskDog("Siberian Husky","male");
		huskdog.show();
		huskdog.eat();
	}
}

class Dog{
	
	protected String name;
	protected String sex;
	
	public Dog(){
		System.out.println("I am Dog Default construction method for!");
	}
	
	public Dog(String name,String sex){
		this.name=name;
		this.sex=sex;
		System.out.println("I am Dog Parametric construction method of!");
	}
	
	//Improve code maintainability
	public void eat(){
		System.out.println("having dinner!");
	}
}

class HomeDog extends Dog{
	
	public HomeDog(){
		super();
		System.out.println("I am HomeDog Default construction method for!");
	}
	
	public HomeDog(String name){
		this.name=name;
		System.out.println("HomeDog The construction method with parameters is executed!");
	}
	
	public void print(){
		System.out.println("I'm a dog!");
	}
	
	public void eat(){
		//Override the method of the parent class
		System.out.println("I'm a dog,I like eating bones!");
	}
}

class HuskDog extends Dog{
	
	public HuskDog(){
		super();
		System.out.println("I am HuskDog Default construction method for!");
	}
	
	public HuskDog(String name,String sex){
		super(name,sex);//Only in the first sentence
		System.out.println("I am"+super.name+"Parametric construction method of!");
	}
	
	public void show(){
		System.out.println("I am a"+super.name+",I can tear down the house!");
	}
	
	public void eat(){
		super.eat();
		System.out.println("I'm husky,I like beef!");
	}
}

6. Application examples of inheritance

Title:
Realize Cosmetics Management in a cosmetics mall
1. Define a cosmetic name, type and price
2. Define a cosmetic manger
(1) Realize the purchase function
(2) It can output all cosmetics information
3. Use inheritance to realize a function that can sort and output all cosmetics according to unit price
4. Use inheritance to realize a function that only outputs imported cosmetics

/**
	2022-2-20
	Realize Cosmetics Management in a cosmetics mall
	1.Define a cosmetic class name, type and price
	2.Define a cosmetic manger
		(1)Realize the purchase function
		(2)It can output all cosmetics information
	3.Use inheritance to realize a function that can sort and output all cosmetics by unit price
	4.Use inheritance to realize a function that only outputs imported cosmetics
*/
import java.util.Arrays;
import java.util.Scanner;
public class Test35{
	public static void main(String[] args){
		
		Scanner input=new Scanner(System.in);
		System.out.println("Please enter the initial cosmetic library value(integer):");
		int num=input.nextInt();
		
		System.out.println("------------------------------");
		CosmeticManger cm=new CosmeticManger(num);
		cm.add(new Cosmetic("Lux","domestic",30));
		cm.add(new Cosmetic("Chanel","Import",1000));
		cm.add(new Cosmetic("how can one endure","Import",800));
		cm.add(new Cosmetic("Dabao","domestic",20));
		
		cm.allPrintInfo();
		
		System.out.println("------------------------------");
		SortCosmeticManger cm1=new SortCosmeticManger(num);
		cm1.add(new Cosmetic("Lux","domestic",30));
		cm1.add(new Cosmetic("Chanel","Import",1000));
		cm1.add(new Cosmetic("how can one endure","Import",800));
		cm1.add(new Cosmetic("Dabao","domestic",20));
		
		cm1.allPrintInfo();
		
		System.out.println("------------------------------");
		ImportCosmeticManger cm2=new ImportCosmeticManger(num);
		cm2.add(new Cosmetic("Lux","domestic",30));
		cm2.add(new Cosmetic("Chanel","Import",1000));
		cm2.add(new Cosmetic("how can one endure","Import",800));
		cm2.add(new Cosmetic("Dabao","domestic",20));
		
		cm2.allPrintInfo();
		
	}
}

//Use inheritance to realize a function that only outputs imported cosmetics
class ImportCosmeticManger extends CosmeticManger{
	
	public ImportCosmeticManger(){}
	public ImportCosmeticManger(int num){
		super(num);
	}
	
	public void allPrintInfo(){
		//Compare whether the values of two strings are equal. You can't use = =, use equals()
		for(int i=0;i<count;i++){
			if("Import".equals(cs[i].getType())){
				System.out.println(cs[i].getInfo());
			}
		}
	}
}

//The function of sorting and outputting all cosmetics by unit price
class SortCosmeticManger extends CosmeticManger{
	
	public SortCosmeticManger(int num){
		super(num);
	}
	
	//The function of sorting and outputting all cosmetics by unit price
	public void allPrintInfo(){
		
		Cosmetic[] temp=Arrays.copyOf(cs,count);
		
		Cosmetic c=null;
		for(int i=0;i<temp.length-1;i++){
			for(int j=0;j<temp.length-i-1;j++){
				if(temp[j].getPrice()>temp[j+1].getPrice()){
					c=temp[j];
					temp[j]=temp[j+1];
					temp[j+1]=c;
				}
			}
		}
		
		for(Cosmetic cs: temp){
		System.out.println(cs.getInfo());
		}
	}
}

//Cosmetics Management
class CosmeticManger{
	
	protected Cosmetic[] cs;
	protected int count=0;
	
	public CosmeticManger(){}
	public CosmeticManger(int num){
		cs=new Cosmetic[num];
	}
	//Purchase function
	public void add(Cosmetic c){
		int size=cs.length;
		if(count>=size){
			int newLen=size*2;
			cs=Arrays.copyOf(cs,newLen);
		}
		cs[count]=c;
		count++;
	}
	
	//Export all products
	public void allPrintInfo(){
		
		for(int i=0;i<count;i++){
			System.out.println(cs[i].getInfo());
		}
	}
}

//Cosmetics
class Cosmetic{
	
	private String name;//brand
	private String type;//Imported or domestic
	private int price;//Price
	
	public Cosmetic(){}
	public Cosmetic(String name,String type,int price){
		this.name=name;
		this.type=type;
		this.price=price;
	}
	
	public void setName(String name){
		this.name=name;
	}
	public String getName(){
		return name;
	}
	
	public void setType(String type){
		this.type=type;
	}
	public String getType(){
		return type;
	}
	
	public void setPrice(int price){
		this.price=price;
	}
	public int getPrice(){
		return price;
	}
	
	public String getInfo(){
		return "name="+name+"\ttype="+type+"\tprice="+price;
	}
}

7.final keyword

The final keyword indicates the final, the declared attribute value cannot be, the declared method cannot be overridden by subclasses, and the declared class cannot be inherited (Extended)

Use the final keyword to do the following:
Use the final keyword to declare a constant: modify an attribute or modify a local variable (final variable), also known as a constant
Use the final keyword to declare a method: the method is the final method and can only be inherited by subclasses, but cannot be overridden by subclasses
Use the final keyword to declare a class: the class will be transformed into the final class. If there is no subclass, the class modified by final cannot be inherited
Use final in the method parameter. The value of the parameter cannot be modified inside the method (explained in detail in the internal class)

final application:
Define a constant:
public static final int NUM=10;
Define a final method (not commonly used)
Define a final class: usually used in constant classes

/**
	2022-2-20
	final keyword
	1.Use final to declare an attribute, which is a constant. It is recommended to use all uppercase for the naming rules of constants
	2.Constants must be initialized when defined or in the constructor
	3.Methods declared with final cannot be overridden by subclasses
	4.
	
	
*/
public class Test36{
	//private static final int PERSON_NUM=10;
	public static void main(String[] args){
		
		System.out.println(Constant.PERSON_NUM);
	}
}

//Constant class (a kind of tool class): in actual project development, constant class is usually used to define some public, invariant and data in the project
class Constant{
	
	public static final int PERSON_NUM=10;//Number of people
}

class FinalClass{
	
	public final int DAY_NUMBER;//Working days
	
	public FinalClass(){
		DAY_NUMBER=22;
	}
}

8. Abstract class

Abstract class can be understood as the abstract level of class. Thinking, many objects can abstract a class, and many classes can abstract abstract abstract classes

Abstract basic concepts

Many objects with the same characteristics and behavior can be abstracted into a class; Many classes with the same characteristics and behavior can be abstracted into an abstract class
The class declared with the abstract keyword is an abstract class

Rules for abstract classes

Abstract classes can have no abstract methods. Classes with abstract methods must be abstract classes
A non abstract class inherits from an abstract class. An abstract class must implement all abstract methods
An abstract class can inherit an abstract class without implementing the parent class's abstract method
Abstract classes can have method implementations and properties
Abstract classes cannot be instantiated
Abstract classes cannot be declared final
Abstract classes can have construction methods

/**
	2022-2-21
	abstract class
*/
public class Test37{
	public static void main(String[] args){
		
		Man man=new Man();
		man.eat();
		man.move();
		
		Women women=new Women();
		women.eat();
		women.move();
	}
}

//Define an abstract class
abstract class Animal{
	
	public abstract void move();
	//Method declaration. Abstract methods have only declaration but no implementation
}

abstract class Person extends Animal{
	
	private String name;
	
	public abstract void eat();//Abstract method
}

//Concrete classes: concrete classes that inherit abstract classes must implement all abstract methods
class Man extends Person{
	
	public void eat(){
		System.out.println("I'm a man,Like women!");
	}
	
	public void move(){
		System.out.println("I love running!");
	}
}

class Women extends Person{
	
	public void eat(){
		System.out.println("I'm a woman,I like bananas!");
	}
	
	public void move(){
		System.out.println("I like shopping!");
	}
}

9. Interface

Interface is the abstraction of all behaviors. The purpose of interface oriented programming is to make the program easy to maintain and extensible. The interface only defines the standard, not the specific implementation

Concept of interface

An interface is a specification of a set of behaviors, which is defined but not implemented (JDK1.8 default method)
Using the interface can make our program more conducive to change
Interface is one of the quintessence of object-oriented programming system
Object oriented design principle: interface based programming

Interface definition format:
Interface interface name{
Global variables;
Abstract methods;
}

Usage rules of interface

Define an interface and use the interface keyword
In an interface, only constants and abstract methods can be defined, jdk1 After 8, you can define the default implementation method
Interfaces can inherit multiple interfaces, extensions XXX, XXX
A concrete class implementation interface uses the implements keyword
A class can implement multiple interfaces
Abstract classes can implement methods that do not implement interfaces
The method defined in the interface does not declare an access modifier. It defaults to public
Interface cannot have constructor

Object oriented design principles:
Close the modification and expand the development
Interface oriented programming

/**
	2022-2-21
	Interface
	
*/
public class Test38{
	public static void main(String[] args){
		
		Girl girl=new Girl("God");
		girl.sleep();
		girl.eat();
		girl.run();
		girl.print();
		
	}
}

//Interface
interface IEat{
	
	//public abstract void eat();
	void eat();//The method defined in the interface does not have a declaration modifier. It defaults to public abstract
	
	//public static final int NUM=10;
	//Define a constant in the interface
	int NUM=10;//constant
	
	//In jdk1 The new feature after 8 can be inherited by all implementation classes
	public default void print(){
		System.out.println("eat!");
	}
}

interface IRun{
	
	void run();
}

//Multiple interfaces can be inherited (Note: classes can only be inherited individually)
interface ISleep extends IEat,IRun{
	
	void sleep();
}

//The concrete class must implement all methods of the interface
class Girl implements ISleep,IEat{
	
	private String name;
	
	public Girl(){}
	public Girl(String name){
		this.name=name;
	}
	
	public void sleep(){
		System.out.println("I love sleeping!");
	}
	
	public void eat(){
		System.out.println("I am"+name+",I love pork!");
	}
	
	public void run(){
		System.out.println("Run after eating!");
	}
}

10. Polymorphism

Polymorphism is one of the three characteristics of object-oriented and the essence of abstract programming thinking. It is the same as interface oriented programming to write code with abstract thinking and then introduce specific objects in the process of operation

Polymorphism is one of the three characteristics of object-oriented
What is polymorphism?
Various forms of objects in the running process

Polymorphism can be roughly divided into two categories

(1) Method overloading and rewriting
(2) Polymorphism of objects

Conclusion: writing code for abstract types in programming is called abstract oriented programming (or interface oriented programming)
Parent classes are usually defined as abstract classes and interfaces

Polymorphism of objects

Object polymorphism is derived from multiple classes in an inheritance relationship
Convert instance to child class
Format: parent class, parent class object = child class instance; (- > automatic conversion)
Take the basic data type operation as an example: int l = 'a';
(because the capacity of char is smaller than int, it can be completed automatically)

Downward Transformation: convert the parent class instance to the child class instance
Format: subclass subclass object = (subclass) parent class instance; Instance conversion
Take the basic data type operation as an example: char c=(char)97;
Because the integer is 4 bytes larger than char 2 bytes, it needs to be forced

Polymorphism summary

Method overloading and rewriting are polymorphic instances of methods
Multiple subclasses are multiple forms in the parent class
The parent class reference can point to the child class object, which is automatically converted
The subclass object points to the parent class reference and needs to be cast (Note: the type will not keep exceptions)
In the actual development, try to use the parent class reference (which is more conducive to expansion)

/**
	2022-2-21
	Polymorphism
	
*/
public class Test39{
	public static void main(String[] args){
		
		System.out.println("----------------------------------");
		HomeChicken hc=new HomeChicken("Xiao Hong");
		hc.eat();
		
		YeChicken yc=new YeChicken("Little pheasant");
		yc.eat();
		
		//Use the application of the parent class to point to the sub class object (use the large type to represent the small type), and automatic conversion (upward transformation)
		System.out.println("----------------------------------");
		Chicken hc1=new HomeChicken("Xiaohong 1");
		hc1.eat();
		
		Chicken yc1=new YeChicken("Little pheasant 1");
		yc1.eat();
		
		System.out.println("----------------------------------");
		hc1=yc1;
		hc1.eat();
		
		System.out.println("----------------------------------");
		//eat(hc);// correct
		
		System.out.println("----------------------------------");
		Chicken jianjiaochicken=new JianJiaoChicken("Screaming chicken!");
		eat(jianjiaochicken);
	}
	
	//Abstract (granularity) object oriented programming (interface oriented programming)
	public static void eat(Chicken c){
		System.out.println("The chickens eat!");
		c.eat();
		//Force conversion
		JianJiaoChicken jianjiaochicken=(JianJiaoChicken)c;//Large to small
		jianjiaochicken.song();
		
		//c.song();// error
	}
}

//chicken
abstract class Chicken{
	
	private String name;
	
	public Chicken(){}
	public Chicken(String name){
		this.name=name;
	}
	
	public void setName(String name){
		this.name=name;
	}
	public String getName(){
		return name;
	}
	
	public abstract void eat();
}

//Domestic chicken
class HomeChicken extends Chicken{
	
	public HomeChicken(){}
	public HomeChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println(this.getName()+",I like rice");
	}
}

//pheasant
class YeChicken extends Chicken{
	
	public YeChicken(){}
	public YeChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println(this.getName()+",I like eating insects");
	}
}

//Screaming chicken
class JianJiaoChicken extends Chicken{
	
	public JianJiaoChicken(){}
	public JianJiaoChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println("I am"+this.getName()+",I don't eat!");
	}
	
	public void song(){
		System.out.println("Cluck, cluck,I'm screaming chicken!");
	}
}

11.instanceof keyword

Note: instanceof keyword is a good weapon to verify the body of the object, which is simple and reliable

instanceof is used to check whether the object is of the specified type. It is usually used when the parent reference is cast into a subclass reference to avoid type conversion exception (classCastException)

The syntax format is as follows:
Object instanceof type – returns a boolean type value
This statement is generally used to judge whether an object is an instance of a class. It returns true or false

Design rule of parent class

Through the instanceof keyword, we can easily check the type of object, but if there are too many subclasses of a subclass, this judgment is still cumbersome, so how to design a parent class?
The parent class is usually designed as an abstract class or interface, in which the interface is given priority. If the interface cannot be satisfied, the abstract class is considered
A concrete class does not inherit from another concrete class as much as possible. The advantage is that there is no need to check whether the object is the object of the parent class

/**
	2022-2-21
	Polymorphism
	
*/
public class Test39{
	public static void main(String[] args){
		
		System.out.println("----------------------------------");
		HomeChicken hc=new HomeChicken("Xiao Hong");
		hc.eat();
		
		YeChicken yc=new YeChicken("Little pheasant");
		yc.eat();
		
		//Use the application of the parent class to point to the sub class object (use the large type to represent the small type), and automatic conversion (upward transformation)
		System.out.println("----------------------------------");
		Chicken hc1=new HomeChicken("Xiaohong 1");
		hc1.eat();
		
		Chicken yc1=new YeChicken("Little pheasant 1");
		yc1.eat();
		
		System.out.println("----------------------------------");
		hc1=yc1;
		hc1.eat();
		
		System.out.println("----------------------------------");
		//eat(hc);// correct
		
		System.out.println("----------------------------------");
		Chicken jianjiaochicken=new JianJiaoChicken("Screaming chicken!");
		eat(jianjiaochicken);
		
		System.out.println("----------------------------------");
		eat(hc);
		eat(yc);
		
		
	}
	
	//Abstract (granularity) object oriented programming (interface oriented programming)
	public static void eat(Chicken c){
		System.out.println("The chickens eat!");
		c.eat();
		//When we need to cast the instance of the parent class into a subclass reference, in order to
		//Avoid type conversion exceptions Java lang.ClassCastException
		//Then we need to make type judgment before conversion
		if(c instanceof JianJiaoChicken){
			//The condition is that the object itself and the parent type of the object can pass the check
			//Force conversion
			JianJiaoChicken jianjiaochicken=(JianJiaoChicken)c;//Large to small
			jianjiaochicken.song();
		}
		//c.song();// error
	}
}

//chicken
abstract class Chicken{
	
	private String name;
	
	public Chicken(){}
	public Chicken(String name){
		this.name=name;
	}
	
	public void setName(String name){
		this.name=name;
	}
	public String getName(){
		return name;
	}
	
	public abstract void eat();
}

//Domestic chicken
class HomeChicken extends Chicken{
	
	public HomeChicken(){}
	public HomeChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println(this.getName()+",I like rice");
	}
}

//pheasant
class YeChicken extends Chicken{
	
	public YeChicken(){}
	public YeChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println(this.getName()+",I like eating insects");
	}
}

//Screaming chicken
class JianJiaoChicken extends Chicken{
	
	public JianJiaoChicken(){}
	public JianJiaoChicken(String name){
		super(name);
	}
	
	public void eat(){
		System.out.println("I am"+this.getName()+",I don't eat!");
	}
	
	public void song(){
		System.out.println("Cluck, cluck,I'm screaming chicken!");
	}
}

12. Abstract class application template method pattern

Note: the essence of the template method pattern is to define an algorithm framework, that is, to abstract the common, which is very useful for the design of the underlying framework in the future

Template method pattern: defines the skeleton of an algorithm in operation, and delays the implementation of some variable parts to subclasses
The template method pattern allows subclasses to redefine some specific steps of an algorithm without changing the structure of the algorithm

/**
	2022-2-21
	Template method mode
*/
public class Test40{
	public static void main(String[] args){
		
		UserManger um=new UserManger();
		um.action("admin","add");
	}
}

abstract class BaseManger{
	
	public void action(String name,String method){
		if("admin".equals(name)){
			execute(method);
		}else{
			System.out.println("You don't have permission to operate!");
		}
	}
	
	public abstract void execute(String method);
}

class UserManger extends BaseManger{
	
	//User login authentication
	//The following operations can be performed only after the verification is successful
	public void execute(String method){
		if("add".equals(method)){
			System.out.println("An add operation was performed");
		}
		else if("del".equals(method)){
			System.out.println("Delete operation performed!");
		}
	}
}

class ClassManger{
	
}

13. Interface application - policy mode

Policy mode is very commonly used. An interface has multiple implementations, and different implementations are encapsulated independently. They can be converted to each other according to runtime requirements, so the maintainability is strong. The new interface implementation will not affect other implementation classes

The policy pattern defines a series of algorithms, encapsulates each algorithm and can be used interchangeably. The policy pattern allows the algorithm to change independently from the customer application using it

OO design principles

Interface oriented programming (Abstract oriented programming)
Package change
Use more combination and less inheritance

/**
	2022-2-22
	
*/
public class Test41{
	public static void main(String[] args){
		
		BaseService user=new UserService();
		user.setISave(new FileISave());
		user.add("Xiao Hong");
		user.setISave(new NetISave());
		user.add("Xiao Ming");
		
	}
}

//Abstract the variable behavior and define a series of algorithms
interface ISave{
	
	public void save(String data);
}

class FileISave implements ISave{
	
	public void save(String data){
		System.out.println("Save data to a file..."+data);
	}
}

class NetISave implements ISave{
	
	public void save(String data){
		System.out.println("Save data to the network..."+data);
	}
}


abstract class BaseService{
	
	private ISave iSave;
	
	public void setISave(ISave iSave){
		this.iSave=iSave;
	}
	
	public void add(String data){
		System.out.println("Check data validity!");
		iSave.save(data);
		System.out.println("The data has been saved!");
	}
} 

class UserService extends BaseService{
	
}

14.Object class

The ancestor Object of all classes is called the root class, so all classes naturally have methods inherited from these objects, such as toString(),hashCode(),equals()

The Object class is the root class of the class hierarchy

Each class uses Object as a superclass, and all objects (including arrays) implement the methods of this class
All classes are subclasses of Object

/**
	2022-2-22
	
*/
public class Test42{
	public static void main(String[] args){
		Student stu=new Student("Xiao Hong",12,23);
		System.out.println(stu.toString());
		
		String str1=new String("Xiao Hong");
		String str2=new String("Xiao Hong");
		System.out.println(str1.equals(str2));
		
		//After overriding the equals method
		Student s1=new Student("Xiao Ming",1,1);
		Student s2=new Student("Xiao Ming",1,1);
		System.out.println(s1.equals(s2));
		
		
	}
}

class Student{
	
	private String name;
	private int sid;
	private int age;
	
	public Student(){}
	public Student(String name,int sid,int age){
		this.name=name;
		this.sid=sid;
		this.age=age;
	}
	
	//Override the toString() method in the Object class
	public String toString(){
		return "name="+this.name+"\tsid="+this.sid+"\t age="+this.age;
	}
	
	//Override the equals() method in the Object class
	public boolean equals(Object obj){
		
		if(this==obj){
			return true;
		}
		if(obj instanceof Student){
			Student s=(Student)obj;
			if(!this.name.equals(s.name)){
				return false;
			}
			if(this.sid!=s.sid){
				return false;
			}
			if(this.age!=s.age){
				return false;
			}
			return true;
		}
		return false;
	}
}

15. Simple factory mode

Factory pattern is widely used. The essence is to obtain objects through factory classes rather than directly create objects. The advantage is that it does not depend on the specific object type to be created, so as to achieve the purpose of decoupling

The simple factory pattern is the simplest and most practical pattern in the factory pattern family. A factory object determines which product class instance to create

/**
	2022-2-22
	Simple factory mode is that a factory object determines which product class instance to create,
	Simple factory model is the simplest and most practical model in the factory model family
*/
public class Test43{
	public static void main(String[] args){
		//The user and the user are coupled and dependent. When the user changes, it will affect the user
		//Use factory mode to reduce the dependence between the two
		Product phone=new Phone();
		phone.work();
		
		phone=ProductFactory.getProduct("phone");
		phone.work();
		
		Product computer=ProductFactory.getProduct("computer");
		computer.work();
		
	}
}

//Simple factory mode
//Factory class
class ProductFactory{
	
	public static Product getProduct(String method){
		if("phone".equals(method)){
			return new Phone();
		}else if("computer".equals(method)){
			return new Computer();
		}else{
			return null;
		}
	}
}

interface Product{
	
	public void work();
}

class Phone implements Product{
	
	public void work(){
		System.out.println("Mobile phones,The phone starts working...");
	}
}

class Computer implements Product{
	
	public void work(){
		System.out.println("Computer,The computer began to work...");
	}
}

16. Static proxy mode

Note: the proxy mode is to control the target object through the proxy object

Proxy mode: provides a proxy for other objects to control access to this object
Proxy mode is the representative of "real object". It introduces a certain degree of indirectness when accessing objects, because this indirectness can be used for many purposes

/**
	2022-2-21
	
*/
public class Test44{
	public static void main(String[] args){
		
		Action user=new UserAction();
		Action target=new ActionProxy(user);
		target.doAction();
	}
}

class ActionProxy implements Action{
	
	private Action target;//Proxied object
	
	public ActionProxy(){}
	public ActionProxy(Action target){
		this.target=target;
	}
	
	public void doAction(){
		long startTime=System.currentTimeMillis();
		target.doAction();//Actions performed
		long endTime=System.currentTimeMillis();
		System.out.println("The total time is"+(endTime-startTime));
	}
}

interface Action{
	
	public void doAction();
}

class UserAction implements Action{
	
	public void doAction(){
		for(int i=0;i<100;i++){
			System.out.println("The first"+(i+1)+"Execute user action!");
		}
	}
}

17. Adapter mode

The MethodInterceptor adapter in Spring is used to solve the problem that Aop's method interceptor must implement MethodInterceptor

Adapter pattern: convert the interface of a class into another interface desired by the customer The adapter pattern allows classes that cannot work together because of interface incompatibility to work together

OO (object oriented) design principles

Interface oriented programming (Abstract oriented programming)
Package change
Use more combination and less inheritance
It is closed for modification and open for extension

/**
	2022-2-22
	
*/
public class Test45{
	public static void main(String[] args){
		
		PowerA a=new PowerAIplm();
		work(a);
		
		//Using adapter to output powerb in work method
		PowerB b=new PowerBIplm();
		Adapter adapter=new Adapter(b);
		work(adapter);
		
		Dog dog=new Dog();
		dog.eat();
		Cat cat=new Cat();
		cat.eat();
		
	}
	
	public static void work(PowerA a){
		System.out.println("on connection...");
		a.insert();
		System.out.println("Ending...");
	}
}

interface Aniaml{
	public void eat();
	public void run();
	public void sound();
	public void heard();
}

//Adapter abstract class
abstract class AnimalFunction{
	public void eat(){}
	public void run(){}
	public void sound(){}
	public void heard(){}
}
class Dog implements Aniaml{
	public void eat(){
		System.out.println("I'm a puppy,I like eating bones!");
	}
	public void run(){}
	public void sound(){}
	public void heard(){}
}

/* 
	If only one of several methods in the interface is implemented,
	Abstract classes are more appropriate
	You don't have to rewrite every method
 */
class Cat extends AnimalFunction{
	public void eat(){
		System.out.println("I am a kitten,I like to eat small fish!");
	}
}

//Fit B to the adapter of A
class Adapter implements PowerA{
	
	private PowerB b;
	
	public Adapter(){}
	public Adapter(PowerB b){
		this.b=b;
	}
	
	public void insert(){
		b.connect();
	}
}

interface PowerB{
	
	public void connect();
}

class PowerBIplm implements PowerB{
	
	public void connect(){
		System.out.println("electric machinery B start-up...");
	}
}

interface PowerA{
	
	public void insert();
}

class PowerAIplm implements PowerA{
	
	public void insert(){
		System.out.println("electric machinery A start-up...");
	}
}

18. Internal class

Note: the concept of inner class breaks the definition of class to some extent, but in some complex class designs, inner class solves the problem that Java cannot inherit more

An inner class is a class defined inside a class
Member inner class
The format is as follows:
class Outer{
class Inner{}
}

Compiling the above code will produce two files:
Outer. Classes and outersinner class.

Method inner class

An inner class can be defined in a method in addition to being a member of a class

be careful:

A method inner class can only be defined and instantiated within the method of the inner class, and cannot be instantiated outside this method
Method internal class objects cannot use non final local variables of the method in which the internal class is located

The format is as follows:
class Outer{
public void doSomething(){
class Inner{
public void seeOuter(){}
}
}
}

Static inner class

Define a static inner class inside a class:
Static means that the inner class can be accessed without external objects like other static members
Static nested classes can only access static members and methods of external classes
class Outer{
static class Inner{}
}
class Test{
public static void main(String[] args){
Outer.Inner n=new Outer.Inner();
}
}

Anonymous Inner Class

An anonymous inner class is an inner class without a name

Three cases of anonymous inner classes

Inherited anonymous inner class
Interface style anonymous inner class
Parameterized anonymous inner class

When using anonymous inner classes, remember the following principles:
There can be no constructor, only one instance
Cannot define any static member, static method
Cannot be public,protected,private,static
It must be behind new to implicitly implement an interface or a class
Anonymous inner classes are local, so all restrictions on local inner classes apply to them

Question: local internal classes must use final to access local variables. Why?

When calling this method, if the local variable is not decorated with final, its life cycle is the same. When the method is called, it will be put into the stack. After the method ends, it will pop up and disappear. If the local internal class object does not disappear immediately, it is obvious that you can't use this local variable. If you use final decoration, it will enter the constant pool when the class is loaded, Even if the method bounces the stack and the constants in the constant pool are still there, they can continue to be used
Note: in jdk1 This feature is canceled in 8 (the variables used in the local internal class must be displayed with the final modifier, and the compiler adds final to this variable by default)

Role of internal classes

Each inner class can independently inherit from an (Interface) Implementation), so whether the outer class has inherited an (Interface) implementation or not has no impact on the inner class Without the ability of internal classes to inherit multiple concrete or abstract classes, some design and programming problems are difficult to solve From this point of view, the inner class makes the solution of multiple inheritance complete, the interface solves some problems, and the inner class effectively implements "multiple inheritance"

How do we choose in project development?

Member: member inner class / static inner class
Local: Method inner class / anonymous inner class
Members that depend on external class objects, internal classes, internal classes of methods, and anonymous internal classes
Static inner classes do not depend on objects of outer classes Therefore, we give priority to selecting static inner classes in the project (no memory leakage)

/**
	2022-2-23
	Inner class
	1.Member inner class, a class defined directly in the class
	2.Method internal class, which defines a class within a method in a class
	3.Static inner class
*/
public class Test46{
	public static void main(String[] args){
		
		Outer out=new Outer();
		
		//Create an instance of a member's inner class externally, because the member's inner class needs to depend on the object of the outer class
		/* Outer.Inner inner=out.new Inner();
		inner.print(); */
		out.innerPrint();
		out.doSomething();
		
		//Static inner class usage
		Outer.Inner2 inner2=new Outer.Inner2();
		inner2.print();
		
		out.print1();
		out.print2();
		//Use of parameterized anonymous inner classes
		out.print3(new Dog(){
			public void eat(){
				System.out.println("Dog Parameterized anonymous inner class of interface!");
			}
		});
		
		
	}
}

class Outer{
	
	private String name;
	
	//It is recommended to define a method in the external class to provide an interface for accessing the internal class
	public void innerPrint(){
		Inner inner=new Inner();
		inner.print();
	}
	
	
	//Member inner class
	class Inner{
		public void print(){
			System.out.println("Member inner class Inner");
		}
	}
	
	
	//Method inner class
	//A local variable in a method or a parameter of a method must actually be a constant, that is, declared by the final modifier
	public void doSomething(){
		final int x=10;
		class Inner1{
			public void print(){
				System.out.println("Method inner class Inner1!"+x);
			}
		}
		Inner1 inner1=new Inner1();
		inner1.print();
	}
	//You cannot provide an interface to a method in a method's inner class outside
	
	
	//Static inner class
	//Non static variables other than static inner classes cannot be accessed
	static class Inner2{
		public void print(){
			System.out.println("Static inner class!");
		}
	}
	
	
	//Anonymous Inner Class 
	//Inheritance
	public void print1(){
		Cat cat=new Cat(){
			public void eat(){
				System.out.println("abstract Cat Class's inherited anonymous inner class!");
			}
		};
		cat.eat();
	}
	//Interface type
	public void print2(){
		Dog dog=new Dog(){
			public void eat(){
				System.out.println("Dog Interface anonymous inner class of interface!");
			}
		};
		dog.eat();
	}
	//Parametric formula
	public void print3(Dog dog){
		dog.eat();
	}
}

interface Dog{
	public void eat();
}

abstract class Cat{
	public abstract void eat();
}

/* class A extends B{
	class D extends C{
		
	}
} */

19. Linked list of data structure

recursive algorithm
Note: the rules of recursive algorithm should be mastered. If the level is too deep, it is easy to overflow memory. Recursion is a double-edged sword. Use it with caution

In the linked list data structure, we need to use recursive algorithm
Recursive algorithm is a process of calling its own algorithm directly or indirectly. In computer programming, recursive algorithm is very effective in solving a large class of problems. It is often described indirectly and easy to understand

Recursion must have an exit
Recursive memory consumption is large and prone to memory overflow
The more hierarchical calls, the more dangerous

/**
	2022-2-24
	recursive algorithm
	
*/
public class Test47{
	public static void main(String[] args){
		
		int result=factorials1(10);
		System.out.println("Calculate the factorial of 10 in a circular manner:"+result);
		
		result=factorials2(10);
		System.out.println("\n The factorial of 10 is calculated by recursive algorithm:"+result);
		result=factorials2(100);
		System.out.println("\n Memory overflow in recursive algorithm(go beyond int Range)Time:"+result);
	}
	
	//recursive algorithm
	public static int factorials2(int num){
		if(num==1)return 1;
		return num*factorials2(num-1);
	}
	
	//Factorial calculation in cyclic mode
	public static int factorials1(int num){
		int result=num;
		int i=num-1;
		do{
			result=result*i;
			i--;
		}while(i>1);
		return result;
	}
}

Linked list

Linked list is a common basic data structure. It is a linear list, but it does not store data in a linear order. Instead, it stores the pointer of the next node in each node instance

/**
	2022-2-25
	Linked list of data structure
*/
public class Test48{
	public static void main(String[] args){
		
		//test
		//add to
		NodeManager node=new NodeManager(1);
		node.add(2);
		node.add(3);
		node.add(4);
		node.add(5);
		node.add(6);
		//Print
		node.print();
		//delete
		node.del(6);
		node.print();
		//Modify node
		node.updata(5,10);
		node.print();
		//Find whether the node exists
		boolean flag=node.find(4);
		if(flag==true){
			System.out.println("There are lookup nodes in the linked list");
		}else{
			System.out.println("There is no lookup node in the linked list");
		}
		//Insert Knot 
		node.insert(0,13);
		node.insert(4,11);
		node.print();
		node.insert(7,12);
		
	}
}

class NodeManager{
	private Node root;
	
	public NodeManager(){}
	public NodeManager(int data){
		this.root=new Node(data);
	}
	
	//add to
	public void add(int data){
		if(root==null){
			root=new Node(data);
		}else{
			root.addNode(data);
		}
	}
	//Delete Vertex 
	public void del(int data){
		if(root==null){
			System.out.println("Empty linked list,Delete failed!");
		}else{
			if(root.getData()==data){
				root=root.next;
			}else{
				root.delNode(data);
			}
		}
	}
	//Modify node
	public void updata(int oldData,int newData){
		if(root==null){
			System.out.println("Empty linked list,Failed to modify node!");
		}else{
			if(root.getData()==oldData){
				root.setDate(newData);
				System.out.println("Node modified successfully!");
			}else{
				root.updataNode(oldData,newData);
			}
		}
	}
	//Find whether the node exists
	public boolean find(int data){
		if(root==null){
			System.out.println("Empty linked list,Node does not exist!");
			return false;
		}else{
			if(root.getData()==data){
				return true;
			}else{
				return root.findNode(data);
			}
		}
	}
	//Insert Knot 
	public void insert(int index,int data){
		if(index==0){
			Node node=new Node();
			node.next=root.next;
			root.next=node;
			node.data=root.data;
			root.data=data;
			System.out.println("Successfully inserted root node!");
		}else{
			root.insertNode(index,data);
		}
	}
	//Print all nodes
	public void print(){
		if(root!=null){
			System.out.print(root.getData());
			root.printAllNode();
			System.out.println();
		}
	}
	
	
	private class Node{
		private int data;
		private Node next;//Treat the current type as a property
		
		public Node(){}
		public Node(int data){
			this.data=data;
		}
		
		public void setDate(int data){
			this.data=data;
		}
		
		public int getData(){
			return data;
		} 
		
		//Add node
		public void addNode(int data){
			if(this.next==null){
				this.next=new Node(data);
			}else{
				this.next.addNode(data);
			}
		}
		
		//Delete Vertex 
		public void delNode(int data){
			if(this.next==null){
				System.out.println("There is no deletion value in the linked list,Delete failed!");
			}else{
				if(this.next.data==data){
					this.next=this.next.next;
					System.out.println("Deletion value exists in linked list,Deleted successfully!");
				}else{
					this.next.delNode(data);
				}
			}
		}
		
		//Modify node
		public void updataNode(int oldData,int newData){
			if(this.next==null){
				System.out.println("There is no old data in the linked list,Failed to modify node!");
			}else{
				if(this.next.data==oldData){
					this.next.data=newData;
					System.out.println("Node modified successfully!");
				}else{
					this.next.updataNode(oldData,newData);
				}
			}
		}
		
		//Find whether the node exists
		public boolean findNode(int data){
			if(this.next==null){
				return false;
			}else{
				if(this.next.data==data){
					return true;
				}else{
					return this.next.findNode(data);
				}
			}
		}
		
		//Insert Knot 
		public void insertNode(int index,int data){
			if(this.next==null){
				System.out.println("Out of range,Unable to insert node!");
			}else{
				if(index==1){
					Node node=new Node(data);
					node.next=this.next;
					this.next=node;
					System.out.println("Successfully inserted node!");
				}else{
					this.next.insertNode(index-1,data);
				}
			}
		}
		
		//Print all nodes
		public void printAllNode(){
			if(this.next!=null){
				System.out.print("->"+this.next.data);
				this.next.printAllNode();
			}
		}
		
	}
}

Only by mastering the advantages and disadvantages of array and linked list can we know how to choose when using. The dynamic array based on array includes ArrayList and LinkedList
Array is suitable for searching, traversal and fixed length
The linked list is suitable for insertion and deletion. It should not be too long, otherwise the traversal performance will be reduced

20. Basic data type packaging

Note: there is a design principle "everything is an object" in Java. The basic data types in java do not conform to this design idea at all. Because the eight basic data types are not reference data types, jdk1.0 is used to solve this problem in Java After 5, eight basic data types of packaging classes were introduced

The eight packaging categories are divided into two types:
Number: integer, short, long, double, float and byte are subclasses of number, representing a number
Object: character and Boolean are direct subclasses of object

Packing and unpacking operation

Converting a basic data type to a wrapper class is called a boxing operation Converting a wrapper class to a basic data type is called unpacking
method:
byteValue(): unpack the byte packing class to byte
doubleValue(): unpack the double packing class as double
floatValue(): unpack the float packing class as float
intValue(): unpack Integer packing class to int
longValue(): unpack the long packing class as long
shortValue(): unpack the short packaging class as short

Transformation operation

In the wrapper class, a string can be changed to the specified basic data type, which is usually used more when inputting data
Note: during the transformation operation, the string must be composed of numbers, otherwise an error will occur

Sharing mode

It uses shared objects to minimize memory usage and share as many similar objects as possible; It is suitable when a large number of objects are only repeated, resulting in unacceptable use of a large amount of memory Usually, some states in an object can be shared
The common practice is to put them in the external data structure and pass them to the shared element when needed
Use sharing technology to effectively support a large number of fine - grained objects

/**
	2022-2-25
	Basic data type packing class
*/
public class Test50{
	public static void main(String[] args){
		
		//Packing: convert the basic data type into packing class, which is called automatic packing
		Integer i1=new Integer(10);
		//Converting a packaging class to a basic data type is called automatic unpacking
		int i2=i1.intValue();
		
		Integer i3=10;//Abbreviation, suggested method
		
		Integer i4=new Integer("123");
		
		//Converts a numeric string to type int
		String num1="12";
		int i5=Integer.parseInt(num1);
		System.out.println(i5);
		
		Integer x1=new Integer(10);
		Integer x2=new Integer(10);
		System.out.println(x1==x2);//false
		System.out.println(x1.equals(x2));//true
		
		Integer x3=new Integer(128);
		Integer x4=new Integer(128);
		System.out.println(x3==x4);//false
		System.out.println(x3.equals(x4));//true
		
		Integer x5=10;
		Integer x6=10;
		System.out.println(x5==x6);//true
		System.out.println(x5.equals(x6));//true
		
		Integer x7=128;//More than one byte, not applicable to sharing mode
		Integer x8=128;
		System.out.println(x7==x8);//false
		System.out.println(x7.equals(x8));//true
	}
}

21. Package and access modifiers

Package is used to manage multiple java source files, just like our file directory
Define a package: package com vince;
This statement can only appear in the first sentence of the code

Access modifier
Public (same class, same package, different package subclasses, different package non subclasses)
Protected (same class, same package, different package subclasses)
Default (same class, same package)
Private (same class)

Summary of OO (object oriented) principles

(1) Opening and closing principle
A software entity, such as classes, modules and functions, should be open to extensions and closed to modifications
(2) Synthesis / aggregation Reuse Principle
If some functions of the new object have been realized in the created object, try to use the functions provided by the existing object to make it a part of the new object instead of re creating it
(3) Dependency Inversion Principle
The high-level module should not rely on the low-level module, and both should rely on its abstraction; Abstract should not rely on details, details should rely on abstraction
(4) Interface isolation principle
The client should not rely on interfaces it does not need; The dependence of one class on another should be based on the smallest interface
(5) Dimitt's law
One object should have minimal knowledge of other objects
(6) Richter substitution principle
All references to the base class must be able to use its subclass objects transparently
(7) Single responsibility principle
Do not have more than one reason for class change, that is, a class is responsible for only one responsibility

Keywords: Java Back-end

Added by darkerstar on Fri, 25 Feb 2022 12:28:34 +0200