Getting started with Java | 6_ Object oriented - next

1, Keyword: static

Static: static

1. Structures that can be modified: mainly used to modify the internal structure of a class

Properties, methods, code blocks, inner classes

2.static modification attribute: static variable (or class variable)

 * 	    2.1 Property, whether to use static Modification is divided into static attributes  vs Non static attribute(Instance variable)
 * 		   Instance variable: we have created multiple objects of the class, and each object independently holds a set of non static attributes in the class. When modifying a non static property in one object, it will not result in the modification of the same property value in other objects.
 *           Static variable: we create multiple objects of the class, and multiple objects share the same static variable. When a static variable is modified through an object, it will cause other objects to call the static variable. It is modified.
 * 	    2.2 static Additional description of modified attributes:
 * 		 ① Static variables are loaded as the class is loaded. Can pass"class.Static variable"Called in the same way
 *          ② Static variables are loaded before objects are created.
 *          ③ Since the class will only be loaded once, the static variable will only exist in memory: in the static field of the method area.
 *          
 *          ④		Class variable	Instance variable
 *          class		yes		no
 *          object	yes		yes
 *          
 *           2.3 Examples of static attributes: System.out; Math.PI;

3. Static variable memory parsing:

4.static modification methods: static methods and class methods

① It is loaded as the class is loaded, and can be called through "class. Static method"

③ In static methods, only static methods or properties can be called
In non static methods, you can call either non static methods or properties or static methods or properties

5. static notes:

5.1 this keyword and super keyword cannot be used in static methods
5.2 everyone understands the use of static attributes and static methods from the perspective of life cycle.

6. How to determine whether attributes and methods should use the static keyword:

6.1 about attributes

Attributes can be shared by multiple objects and will not vary with different objects.
Constants in classes are also often declared as static

6.2 about methods

The method for operating static properties is usually set to static
Methods in tool classes are traditionally declared as static. For example: Math, Arrays, Collections

7. Use examples

Example 1: Arrays, Math, Collections and other tool classes
Example 2: Singleton mode
Example 3:

class Circle{
	
	private double radius;
	private int id;//automatic recode 
	
	public Circle(){
		id = init++;
		total++;
	}
	
	public Circle(double radius){
		this();
//		id = init++;
//		total++;
		this.radius = radius;
		
	}
	
	private static int total;//Record the number of circles created
	private static int init = 1001;//static declared properties are shared by all objects
	
	public double findArea(){
		return 3.14 * radius * radius;
	}

	public double getRadius() {
		return radius;
	}

	public void setRadius(double radius) {
		this.radius = radius;
	}

	public int getId() {
		return id;
	}

	public static int getTotal() {
		return total;
	}

}

8. Singleton mode

1. Description of design mode

1.1 understanding
Design pattern is the excellent code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice.

1.2 common design patterns --- 23 classic design patterns GOF
There are five kinds of creation mode: factory method mode, abstract factory mode, singleton mode, builder mode and prototype mode.
There are seven structural modes: adapter mode, decorator mode, agent mode, appearance mode, bridge mode, combination mode and sharing mode.
There are 11 behavioral modes: policy mode, template method mode, observer mode, iterator mode, responsibility chain mode, command mode, memo mode, status mode, visitor mode, mediator mode and interpreter mode.

2. Singleton mode

2.1 problems to be solved:
The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance of a class in the whole software system.
2.2 implementation of specific code:
Hungry Han style 1:

class Bank{
	
	//1. Private constructor
	private Bank(){
		
	}
	
	//2. Create class objects internally
	//4. This object must also be declared static
	private static Bank instance = new Bank();
	
	//3. Provide public static methods to return class objects
	public static Bank getInstance(){
		return instance;
	}
}

Hungry man 2: static code blocks are used

class Order{
	
	//1. Private constructor
	private Order(){
		
	}
	
	//2. Declare the current class object, not initialized
	//4. This object must also be declared as static
	private static Order instance = null;

	static{
		instance = new Order();
 }
	
	//3. Declare public and static methods that return the current class object
	public static Order getInstance(){
		return instance;
	}
	
}

Lazy:

class Order{
	
	//1. Private constructor
	private Order(){
		
	}
	
	//2. Declare the current class object without initialization
	//4. This object must also be declared as static
	private static Order instance = null;
	
	//3. Declare public and static methods that return the current class object
	public static Order getInstance(){
		
		if(instance == null){
			
			instance = new Order();
			
		}
		return instance;
	}
}

2.3 comparison of the two methods:

 *   Hungry Han style:	
 *   	Disadvantage: the object takes too long to load.
 *   	Benefit: hungry Chinese style is thread safe
 *   
 *   Lazy: benefit: delay the creation of objects.
 * 	The disadvantage of the current writing method: thread is not safe.--->When the multithreaded content is, modify it again

2, Instructions for using the main() method

 * 1. main()Method as an entry to the program
 * 2. main()Method is also a common static method
 * 3. main()Method can be used as a way for us to interact with the console. (before: use) Scanner)

How to transfer the data obtained by the console to the formal parameter: String[] args?
Runtime: java class name "Tom" "Jerry" "123" "true"

sysout(args[0]);//"Tom"
sysout(args[3]);//"true" -->Boolean.parseBoolean(args[3]);
sysout(args[4]);// Report exception

Summary: a leaf knows autumn
public static void main(String[] args) {/ / method body}

Permission modifier: private default protected pubilc ---- > encapsulation
Modifiers: static \ final \ abstract \native can be used to modify methods
Return value type: no return value / return value -- > Return
Method name: it needs to meet the rules and specifications of identifier naming; "See the name and know the meaning"
Formal parameter list: overload vs override; Parameter value transfer mechanism; Reflect the polymorphism of objects
Method body: to reflect the function of the method

main(){
Person p = new Man();
p.eat();
//p.earnMoney();

Man man = new Man();
man.eat();
man.earnMoney();
}

3, Class structure 4: code block

Class member 4: code block (initialization block) (less important than attributes, methods and constructors)

1. Function of code block: used to initialize class and object information

2. Classification: if a modifier is used in a code block, only static can be used

Classification: static code block vs non static code block

3. Static code block and non static code block

Static code block:

Internal can output statements
Executes as the class loads, and only once
Function: initialize class information
If multiple static code blocks are defined in a class, they are executed in the order of declaration
The execution of static code blocks takes precedence over the execution of non static code blocks
Static code blocks can only call static attributes and static methods, not non static structures

Non static code block:

Internal can output statements
Executes as the object is created
Each time an object is created, a non static block of code is executed
Function: you can initialize the properties of the object when creating the object
If multiple non static code blocks are defined in a class, they are executed in the order of declaration
Static attributes, static methods, or non static attributes and non static methods can be called in non static code blocks

4. When instantiating a subclass object, it involves the loading sequence of static code blocks, non static code blocks and constructors in the parent class and subclass:

Corresponding exercise: leaftest java / Son. java
By parent and child, static first.

5. Assignment order of attributes

 * ①Default initialization
 * ②Explicit initialization/⑤Assignment in code block
 * ③Initialization in constructor
 * ④Once you have an object, you can use"object.attribute"or"object.method"Assign values in the same way
 * 
 * Order of execution:① - ② / ⑤ - ③ - ④

4, Keyword: final

final: final

1. It can be used to modify: classes, methods and variables

2. Specific

2.1 final is used to modify a class: this class cannot be inherited by other classes.
For example: String class, System class and StringBuffer class
2.2 final is used to modify a method: it indicates that this method cannot be overridden
For example: getClass() in Object class;
2.3 final is used to modify variables: in this case, the "variable" is called a constant

  1. final modified attribute: the location of assignment can be considered: explicit initialization, initialization in code block and initialization in constructor
  2. Final modifier local variable: especially when final modifier parameter is used, it indicates that this parameter is a constant. When we call this method, we assign an argument to the constant formal parameter. Once assigned, this parameter can only be used in the method body, but it cannot be re assigned.

static final is used to modify the attribute: global constant

5, Keywords: abstract

abstract: abstract

1. Can be used to modify: class and method

2. Specific

Abstract modifier class: abstract class

This class cannot be instantiated
There must be a constructor in the abstract class to be called when subclass instantiation (involving the whole process of subclass object instantiation)
During development, subclasses of abstract classes will be provided to instantiate subclass objects and complete relevant operations -- > premise of abstract use: inheritance

Abstract modifier: abstract method

Abstract methods are only method declarations, not method bodies
A class containing abstract methods must be an abstract class. Conversely, there can be no abstract methods in an abstract class.
A subclass can be instantiated only after it overrides the abstract method in the parent class
If the subclass does not override the abstract method in the parent class, the subclass is also an abstract class and needs to be modified with abstract

3. Precautions:

1.abstract cannot be used to modify structures such as attributes and constructors
2.abstract cannot be used to modify private methods, static methods, final methods, and final classes

4. Application examples of Abstract:

Example 1:

Example 2:

abstract class GeometricObject{
public abstract double findArea();
}
class Circle extends GeometricObject{
private double radius;
public double findArea(){
		return 3.14 * radius * radius;
};
}

Example 3: abstract classes designed in IO streams: InputStream/OutputStream / Reader /Writer. Abstract read() and write() methods are defined inside.

5. The formwork method is divided into design modes

  1. Problems solved
    When implementing an algorithm in software development, the overall steps are very fixed and common. These steps have been written in the parent class. But some parts are changeable, changeable
    Part can be abstracted out for different subclasses to implement. This is a template mode.

  2. give an example

abstract class Template{
	
	//Calculate the time it takes for a piece of code to execute
	public void spendTime(){
		
		long start = System.currentTimeMillis();
		
		this.code();//Uncertain part, changeable part
		
		long end = System.currentTimeMillis();
		
		System.out.println("Time spent:" + (end - start));
		
	}
	
	public abstract void code();
	
}

class SubTemplate extends Template{

	@Override
	public void code() {
		
		for(int i = 2;i <= 1000;i++){
			boolean isFlag = true;
			for(int j = 2;j <= Math.sqrt(i);j++){
				
				if(i % j == 0){
					isFlag = false;
					break;
				}
			}
			if(isFlag){
				System.out.println(i);
			}
		}

	}
	
}
  1. Application scenario

5, Keywords: interface

interface: interface

1. Instructions

 * 1.Interface use interface To define
 * 2.Java In, interface and class are two structures in parallel
 * 3.How to define an interface: define members in an interface
 * 		
 * 		3.1 JDK7 And before: only global constants and abstract methods can be defined
 * 			>Global constants: public static final of.However, when writing, it can be omitted
 * 			>Abstract method: public abstract of
 * 			
 * 		3.2 JDK8: In addition to defining global constants and abstract methods, you can also define static methods and default methods (omitted)
 * 
 * 4. Constructor cannot be defined in interface! This means that the interface cannot be instantiated
 * 
 * 5. Java In development, interfaces are implemented by letting classes(implements)To use.
 *    If the implementation class overrides the abstract methods in the interface, the implementation class can be instantiated
 *    If the implementation class does not cover the abstract methods in the interface, the implementation class is still an abstract class
 *    
 * 6. Java Class can implement multiple interfaces   --->Made up Java Limitations of single inheritance
 *   Format: class AA extends BB implements CC,DD,EE
 *   
 * 7. Interfaces can be inherited from one interface to another, and multiple interfaces can be inherited
 * 
 * *******************************
 * 8. The specific use of the interface reflects polymorphism
 * 9. Interface can actually be regarded as a specification

2. Examples:

class Computer{
	
	public void transferData(USB usb){//USB usb = new Flash();
		usb.start();
		
		System.out.println("Details of specific transmission data");
		
		usb.stop();
	}
	
	
}

interface USB{
	//Constant: defines the length, width, maximum and minimum transmission speed, etc
	
	void start();
	
	void stop();
	
}

class Flash implements USB{

	@Override
	public void start() {
		System.out.println("U Disc opening operation");
	}

	@Override
	public void stop() {
		System.out.println("U Disk end work");
	}
	
}

class Printer implements USB{
	@Override
	public void start() {
		System.out.println("Printer on");
	}

	@Override
	public void stop() {
		System.out.println("Printer finished working");
	}
	
}

experience:

  • 1. The interface also meets polymorphism
  • 2. Interface actually defines a specification
  • 3. Experience interface oriented programming during development!

3. Experience the idea of interface oriented programming

Interface oriented programming: in our application, the structure we call is the interface defined in JDBC, and there will not be API of a specific database manufacturer.

4. New specification of interface in Java 8

//Knowledge point 1: static methods defined in the interface can only be called through the interface.
//Knowledge point 2: by implementing the object of the class, you can call the default method in the interface. If the implementation class overrides the default method in the interface, the overridden method will still be called
//Knowledge point 3: if the default method with the same name and parameter is declared in the inherited parent class and the implemented interface of the subclass (or implementation class), the subclass will call the method with the same name and parameter in the parent class by default without overriding this method. -- > Class priority principle
//Knowledge point 4: if the implementation class implements multiple interfaces and default methods with the same name and parameters are defined in these interfaces, an error will be reported if the implementation class does not rewrite this method. -- > Interface conflict. This requires that we must override this method in the implementation class
/ / knowledge point 5: how to call the parent class in the subclass (or implementation class) method and the method to be rewritten in the interface.

	public void myMethod(){
		method3();//Call the overridden method defined by yourself
		super.method3();//Called is declared in the parent class
		//Call the default method in the interface
		CompareA.super.method3();
		CompareB.super.method3();
	}

5. Interview questions:

What are the similarities and differences between abstract classes and interfaces?
Similarities: cannot be instantiated; Can contain abstract methods.
difference:
1) Explain the definition and internal structure of abstract classes and interfaces (java7,java8,java9)
2) Class: single inheritance interface: multiple inheritance
Classes and interfaces: multiple implementations

6. Agency mode

1. Problems solved

Proxy pattern is a design pattern used more in Java development. Proxy design is to provide a proxy for other objects to control access to this object.

2. Examples

interface NetWork{
	
	public void browse();
	
}

//Proxy class
class Server implements NetWork{

	@Override
	public void browse() {
		System.out.println("Real server access network");
	}

}
//proxy class
class ProxyServer implements NetWork{
	
	private NetWork work;
	
	public ProxyServer(NetWork work){
		this.work = work;
	}
	

	public void check(){
		System.out.println("Inspection before networking");
	}
	
	@Override
	public void browse() {
		check();
		
		work.browse();
		
	}
	
}

3. Application scenarios

7. Design mode of the plant

1. Problems solved

It realizes the separation of creator and caller, that is, the specific process of creating objects is shielded and isolated, so as to improve flexibility.

2. Specific mode

Simple factory mode: used to produce any product in the same hierarchical structure. (for adding new products, the existing code needs to be modified)
Factory method mode: used to produce fixed products in the same hierarchical structure. (any product can be added)
Abstract factory pattern: used to produce all products of different product families. (there is nothing you can do to add new products; support adding product families)

7, Inner class

Inner class: the fifth member of the class

1. Definition: Java allows one class A to be declared in another class B, then class A is the inner class, and class B is called the outer class

2. Classification of internal classes

Member inner class (static, non static) vs local inner class (within method, code block, constructor)

3. Understanding of internal classes of members

On the one hand, as a member of an external class:

 * 			>Calling the structure of an external class
 * 			>Can be static modification
 * 			>It can be modified by four different permissions

On the other hand, as a class:

 * 			> Properties, methods, constructors, etc. can be defined within a class
 * 			> Can be final Modifier to indicate that this class cannot be inherited. Implied, do not use final,Can be inherited
 * 			> Can be abstract modification

4. Member internal class

4.1 how to create an object of a member's internal class? (static, non static)

//Create an instance of a static Dog inner class (static member inner class):
Person.Dog dog = new Person.Dog();

//Create an instance of a non static Bird inner class (non static member inner class):
//Person.Bird bird = new Person.Bird();// FALSE
Person p = new Person();
Person.Bird bird = p.new Bird();

4.2 how do I invoke the structure of external class in the member class?

class Person{
	String name = "Xiao Ming";
public void eat(){
}
//Non static member inner class
	class Bird{
		String name = "cuckoo";
		public void display(String name){
			System.out.println(name);//Formal parameters of method
			System.out.println(this.name);//Properties of the inner class
			System.out.println(Person.this.name);//Properties of external classes
		//Person.this.eat();
		}
	}
}

5. Use of local internal classes:

        //Returns an object of a class that implements the Comparable interface
	public Comparable getComparable(){
		
		//Create a class that implements the Comparable interface: a local inner class
		//Mode 1:
//		class MyComparable implements Comparable{
//
//			@Override
//			public int compareTo(Object o) {
//				return 0;
//			}
//			
//		}
//		
//		return new MyComparable();
		
		//Mode 2:
		return new Comparable(){

			@Override
			public int compareTo(Object o) {
				return 0;
			}
			
		};
		
	}

Note:
In the method of the local inner class (such as: show), if you call the local variable (such as: num) in the method declared by the local inner class (such as: method), you are required to declare this local variable as final.
jdk 7 and earlier: this local variable is required to be explicitly declared final
jdk 8 and later versions: the final declaration can be omitted

Summary:
Member internal classes and local internal classes will generate bytecode files after compilation.
Format: member inner class: outer class $inner class name class
Local internal class: external class $numeric internal class name class

Keywords: Java

Added by Jocka on Tue, 25 Jan 2022 17:10:08 +0200