13, Object oriented enumeration and keywords“

Posted by johnc71 on Thu, 27 Jan 2022 14:26:07 +0100

Article catalogue

  1. static keyword
  2. Internal class Anonymous Inner Class
  3. final modifier
  4. Code block
  5. enumeration

1.static modifier

1.1 static concept: keyword and modifier, indicating static

static is a modifier: the content that can be modified:

Currently, there are members in java code

  1. Can modify common methods
  2. Field [member variable] can be modified
  3. Inner classes can be decorated
  4. External classes cannot be decorated
  5. Local variables cannot be modified;
  6. The constructor cannot be modified

1.2 modify member variables and methods

Access method: class name Members in class (variables, methods)

1.2.1 features after static modification

static class level modifier (the modified member belongs to the class)

When a class is used (new class name (...)), the bytecode file of the class will be loaded into the meta space. When loading, the members decorated with static will be preferentially loaded into the static area. The class loading process will only be executed once, only one copy. After execution, the members of the static modifier will be shared by all objects created with the bytecode file as the template.

For example:

Design a student class with a name name field. Should static be added?

Effect: static modified field: this field is shared by all objects of this class: when an object modifies this field, other objects use this field, which is the modified value

/**
 *	Student class
 */
public class Student {
	/**Modifying name with static will be shared by all objects created with Student template*/
	static String name;
	public Student(String n) {
		name = n;//Assign the passed in n to the member variable name
	}
	public static void testStatic() {
		System.out.println("static Modification method");
	}
	/**
	 * Inner class
	 */
	static class Inner{
	}
}

/**
 *	static Test class
 */
public class StudentTest {

	public static void main(String[] args) {
		//Call parameterized construction, create objects and assign values directly
		Student stu1 = new Student("Lao Wang next door");
		//Print stu1's name
		System.out.println(stu1.name);//Lao Wang next door
		
		//Call parameterized construction, create objects and assign values directly
		Student stu2 = new Student("Old grandson next door");
		//Print stu2's name
		System.out.println(stu2.name);//Old grandson next door
		//Reprint stu1's name
		System.out.println(stu1.name);//Lao sun next door (not Lao Wang next door)
	}
}

Stack fee analysis before and after adding static modification field:

Before adding static:

After adding static:

 

1.3 static function

1. You can avoid creating objects multiple times. For example: Singleton mode

2. Several objects need to have shared data.

3. In general, when modifying member variables, they are used together with public static final. The modified ones are called: global constants are generally named in all uppercase + underscore, such as MAX_VALUE

4. Modification method is just for convenience of calling. Class name Method name (...). For example: Arrays are all tool methods (static) toString(…);

5. Recently, in object-oriented grammar, the methods we usually write are non static, unless we have to use static

1.4 # variable reclassification

Member variables (also known as fields): static (class variables) and non static (instance variables)

static int age; Class variables, member variables (fields) decorated with static;

int age; Instance variable, member variable (field) without static modification;

Detailed classification:

Location  whether there is a static  life cycle (start) life cycle (end)

Class variable √ when the class is loaded √ when the class is unloaded

There is no instance variable in the # class. When # creates an object, the # object loses its reference

When the , method in the local variable , method and no , method in the code block are called, the , method is called

2. Inner class and anonymous inner class

2.1 internal class

What is an inner class? Define a class inside another class, call the inner class the inner class, and call the outer class the outer class.

 

Internal classes can be regarded as members of external classes like fields and methods, and members can be decorated with static.

Static internal class: internal class decorated with static. If the internal class is accessed, the external class name is used directly

Instance internal class: internal class without static modification. Internal class is accessed by objects of external class

Local internal class: the internal class defined in the method, which is generally not used

Anonymous inner class: a special local inner class, which is suitable for classes used only once

For each inner class, the Java compiler generates a separate Class file.

Static and instance internal classes: external class name $internal class name

Local internal class: external class name $numeric internal class name

Anonymous inner class: outer class name $number

2.2 anonymous inner class

In the case of polymorphic USB, when a USB standard device is added, a separate file needs to be used to define a new class.

For example, add a new one USB Standard printer equipment.
public class Print implements IUSB{

    public void swapData() {
        System.out.println("Print....");
    }
}

Install the printer on the motherboard.
public class USBDemo {

    public static void main(String[] args) {
        // Create motherboard object
        MotherBoard board = new MotherBoard();

        // Create printer object
        Print p = new Print();

        //Install the printer on the motherboard
        board.plugin(p);
    }
}

If this Print class only needs to be used once, there is no need to define a separate Java file and use the anonymous inner file directly

To complete.

Anonymous inner class, which can be completed by using parent class constructor and interface name.

For a class, define an anonymous inner class to inherit the parent class (less used):

new parent class constructor ([argument list]){

//The body part of an anonymous inner class

}

For interfaces, define anonymous internal classes to implement interfaces (more often used):

new interface name (){

//The body part of an anonymous inner class

}

Note: the object is not created according to the interface, but a syntax.

board.plugin(new IUSB() {

    public void swapData() {
    
        System.out.println("Print...Print...");
    }

});

In fact, for anonymous internal classes, the bottom layer still creates a bytecode file USBDemo , and its decompile code is:

 

 3.final modifier

3.1 # final concept

Keyword, modifier, indicating the final. Once a member is modified, the member can no longer be modified.

3.2 final function:

Can be modified:

External class: eunuch class, which cannot be inherited

Instance variable: must be assigned at the time of declaration or in the constructor

Class variable: must be assigned at the time of declaration

Instance method: cannot be overridden by subclasses

Class method: cannot be overridden by subclasses

Internal class:

Local variables:

Cannot decorate:

Construction method

Code demonstration:
public class FinalTest {
	/** Instance variable 	 In the heap */
	private final int A;
        private final int B = 1; // Direct assignment when declaring
	
	/** Class variable 	 In static area */
	static final int C = 1; // Direct assignment when declaring
	
	/**
	 * Construction method, final cannot be modified
	 */
	public FinalTest() {
		A = 1; //Assignment in construction method
	}
	
	/**
	 * Instance method, cannot be overridden
	 */
	public final void test() {
		
	}
	
	/**
	 * Class method, cannot be overridden
	 */
	public static final void testStatic() {
		
	}
	
	/**
	 * Internal class, cannot be inherited
	 */
	final class Inner{
		
	}
	
	public static void main(String[] args) {
		final int a; // In stack frame
		a = 2; // Once modified by final, it cannot be modified
		System.out.println(a);
		
//		a = 3; //  Once modified by final, it cannot be modified
	}
}

4. Code block

4.1 what is a code block

Simply think of it as a pair of {};

When you see {}, you should think about the scope;

4.2 code block classification

Static code block

Syntax: directly declared in a class, preceded by a static modifier

static {

/ / generally used to initialize data. Initialization is completed when the class is loaded

① {} directly written in the class, with static modification;

② When the class is loaded, the execution has nothing to do with creating the object, and will only be executed once

③ Prior to the execution of the main method (after loading, the JVM will find the main method to execute)

④ You can do some initialization operations when loading classes (such as loading JDBC drivers)

Local code block (normal code block)

It's basically useless. A pair of {} in the method will not be used alone. It is usually used in conjunction with statements such as if or loop

Construct code block

Syntax: directly declared in the class without static modification

{

//It is generally used in scenarios where multiple construction methods have the same initialization code

The code in this code block will be generated inside the constructor, under super() and above other codes

 }

② Code blocks written directly in the class (without static modification);

③ After compilation, a copy will be copied in each construction method;

④ Creating an object (calling the constructor once) will execute once

⑤ You can initialize the value of the instance field of the object (basically not used)

4.3 master the execution order of each member (including class variables) in the class of inheritance relationship

Execution process with inheritance relationship:

Load from the static code block of the highest parent class, and then load down level by level until the static code block of the current class ends.

Then it starts from the construction code block of the highest parent class, then the construction method, and then executes down level by level until it is executed to the construction code block and construction method of the current class.

public class CodeBlock {
	/**
	 * Static code block: executed only once
	 */
	static {
		//It is generally used to initialize data. Initialization is completed when the class is loaded
		System.out.println("Static code block");
	}
	
	/**
	 * Construction code block: (basically useless) it will be executed every time the object is created
	 */
	{
		//The code in this code block will be generated inside the constructor, under super() and above other codes
		System.out.println("Construct code block");
	}
	
	/**
	 * Construction method
	 */
	public CodeBlock() {
		super();
		//System.out.println("construction code block");
		System.out.println("Construction method!");
	}
	
	public static void main(String[] args) {
		new CodeBlock();
		new CodeBlock();
		
		{//Common code block
			int a = 1;
		}
//		System.out.println(a);// Out of scope
	}

}

5. Enumeration

5.1 introduction of enumeration

Requirement: a class is designed to express gender (the value of gender is relatively fixed: male, female and unknown)

/**
 *	Design a class that represents gender
 *		3 Species: male MAN, female WOMEN, UNKNOWN
 *
 *	Intrusive problem: a class containing other data types is intrusive. Avoid as much as possible.
 */
public class Gender {//Indicates the gender category
//	public static final String MAN = "male"// MAN is an object of String
	//Using String type in the Gender class has intrusive problems. So, can you represent a male with an object of Gender's own type? sure
	public static final Gender MAN = new Gender(); //MAN is an object of Gender
	
//	public static final String WOMEN = "female"// WOMEN is an object of String
	public static final Gender WOMEN = new Gender(); //WOMEN is an object of Gender
	
//	public static final String UNKNOWN = "UNKNOWN"// UNKNOWN is an object of String
	public static final Gender UNKNOWN = new Gender(); //UNKNOWN is an object of Gender
	
	@Override
	public String toString() {
		/*
		 * The desired print format is as follows:
		 * 	MAN print MAN
		 * 	It's WOMEN print girl
		 * 	UNKNOWN print
		 */
		if (this == MAN) {
			return "male";
		}else if (this == WOMEN) {
			return "female";
		}else{
			return "unknown";
		}
	}
}

Test class:
/**
 *	Test gender, enumeration, introduction
 */
public class GenderTest {
	public static void main(String[] args) {
		//Call global constant method, class name Constant name
		System.out.println(Gender.MAN); //male
		System.out.println(Gender.WOMEN); //female
		System.out.println(Gender.UNKNOWN); //unknown
	}

}

Do you think the above code method is very troublesome? So, is there a simpler way? Using enumeration, so what is enumeration?

5.2 enumeration overview

5.2.1 what is enumeration

Enumeration is jdk1 5 introduces a new structure very similar to class;

What problems does enumeration solve?

Enumeration class solves some scenarios with fixed values and simplifies the constant fields in the class.

5.2.2 enumerating functions and usage scenarios

Function: simplify the constant declaration in the class, which makes the code more elegant

Usage scenarios: vip, zodiac, segment, QQ status, blood type, gender, constellation, month, week

5.2.3 basic syntax of enumeration

① Declaration syntax:

public enum enumeration class name{

field

Instance variable

Example method

Class method

Constructor - all constructors in enumeration are private modifiers by default, not public and protected modifiers

Constructor function: it can only be used in the current enumeration class, which is to initialize the instance variable for the current enumeration class object

}

Syntax: 
public enum Gender { //Indicates the gender category
//	MAN, / / equivalent to a constant public static final Gender = new Gender();
	MAN(), // MAN can also be written in this way, which is to call the parameterless construction of the current enumeration class
	WOMEN("female"), // Here is the parameter construction of the String type calling the current enumeration class
	UNKNOWN,
	other; //You can also write in Chinese, but it is not recommended. The suggested writing method is: WOMEN("");
	private String name; // Instance variables belong to each enumeration object, such as man, woman
	
	/**
	 * Nonparametric structure
	 */
	Gender() { // There is an implicit private modifier by default
		
	}
	
	/**
	 * Parametric structure
	 */
	Gender(String name) { // There is an implicit private modifier by default
		this.name = name;
	}
	
	@Override // Example method
	public String toString() {
		if (this == MAN) {
			return "male";
		}else if (this == WOMEN) {
			return "female";
		}else{
			return "unknown";
		}
	}
	
	/**
	 * Class method
	 */
	public static void test() {
	
	}
}

② The bytecode file is also generated after the enumeration class is compiled

③ Each custom enumeration type is (implicitly) inherited from the Enum abstract class, so our enumeration object can call the methods in Enum (see API). However, the inheritance relationship cannot be written out.

//The above gender code is simplified by enumeration
public enum Gender { // Indicates the gender category
	MAN, // The MAN field is equivalent to the original public static final Gender MAN = new Gender(); This sentence
	WOMEN,
	UNKNOWN;
	@Override
	public String toString() { // This method is inherited from Enum in the middle
		if (this == MAN) {
			return "male";
		}else if (this == WOMEN) {
			return "female";
		}else{
			return "unknown";
		}
	}
}

Test code:
/**
 *	Test enumeration
 */
public class GenderTest {

	public static void main(String[] args) {
		//Call global constant method, class name Constant name
		System.out.println(Gender.MAN); // male
		System.out.println(Gender.WOMEN); // female
		System.out.println(Gender.UNKNOWN); // unknown
	}
}

5.4 enumeration precautions

1. Comma is used between fields, and semicolon is used to end the last field

2. You can write Chinese fields, but it is not recommended

3. Enum classes implicitly inherit enum class (the base class of all enum classes), which cannot be displayed or written out

4. The construction method must be private

5.5 two common ways of enumerating

Mode 1 Code:
public enum Gender {
	MAN,
	WOMEN,
	UNKNOWN;
}

Mode 2 Code:
public enum Gender {
	MAN("male"),
	WOMEN("female");
	private String name;
	
	private Gender(String name) {
		this.name = name;
	}
	
	@Override
	public String toString() {
		return this.name;
	}
}


coordination switch Sentence exercise:
/**
 * Test enumeration
 */
public class GenderTest {

	public static void main(String[] args) {
		// Call global constant method, class name Constant name
		Gender gender = Gender.MAN;

		switch (gender) {
			case MAN:
				System.out.println("Male left");
			        break;
			case WOMEN:
				System.out.println("Actress");
			        break;
			default:
				System.out.println("unknown");
			        break;
		}
	}

}

Object oriented closure

Topics: Java Back-end OOP