This article allows you to understand and unblock 11 common modifier syntax descriptions in Java from the most basic underlying principles and application cases in common development


Preface

Modifiers have four use cases in the Java language: member variables, member methods, code blocks, and inner classes. In the daily development process, we will encounter the following 11 common modifiers. This article will help you understand and clear these common modifier syntax descriptions and common development application cases from the most basic bottom layer and principles.

Insert picture description here


One, 11 common Java modifiers

1. Modifier application table

Modifier class Construction method method data Piece Explanation
(default) The class, constructor, method or data field is visible in the package
public Classes, constructors, methods or data fields are visible in any package or program
private Constructor, method or data field is only visible in the class
protected The construction method, method or data field is visible in the package to which it belongs, or visible in any subclass of this class in any package
static Define class methods, class data fields or static initialization modules
final The ultimate class cannot be extended. The ultimate method cannot be modified in the subclass. The ultimate data field is constant
abstract The abstract class must be extended. Abstract methods must be implemented in concrete subclasses
native The method modified with native indicates that it is implemented in a language other than Java
synchronized Only one thread can execute this method at a time
strictfp Use accurate floating point calculation mode to ensure that the calculation results are the same in all Java virtual machines
transient Mark the instance data field so that it is not serialized

2. Comparison of access rights

public > protected > default > private

Note : The following only introduces the 7 commonly used modifier syntax instructions and development application instructions, and the other 4 usages can be viewed in the modifier application table.

Two, public modifier

Syntax description :

  1. Modify classes, methods, and variables. Can be accessed anywhere, public.

Development and application :

  1. In development, usually classes and business methods are decorated with public.

Three, private modifier

Syntax description:

  1. Modify methods, variables, and internal classes. Can only be accessed in this class, private.

Development and application :

  1. In development, usually member variables in entity classes (Entity, Vo) are decorated with private, and getter or
    setter methods are provided to access these variables . In principle, it is not allowed to define private methods.
  2. An entity data table usually corresponds to an entity class.

Four, protected modifier

Syntax description :

  1. Modify methods, variables, and internal classes.
  2. The same package can be accessed, and the subclass can be accessed (the subclass and the parent can be accessed if they are not in the same package).

Development and application :

  1. In development, usually methods or variables are used for inheritance and are decorated with protected.
  2. In inheritance, method rewriting, the access permission of the subclass method must be greater than or equal to the access permission of the parent method.
class Fu {
	public void play() {
	}
}

class Son extends Fu {
	void play() {
	}
}

Five, default (without any access permission modifier)

Syntax description :

  1. Modify classes, methods, and variables.
  2. It can only be accessed in the same package, and the subclass must also be in the same package.

Development and application :

  1. In a project, classes, methods, and variables are usually assigned access permissions based on requirements.

Six, static modifier

1. Static modified member variables (static variables/class variables)

Syntax description :

  1. In Java, variables can be modified by the static keyword to achieve the effect of global variables.
  2. The static modified variable (static variable) belongs to the class, and is allocated to the method area when the class passes the class loader to the jvm for the first time.
  3. Variables without static modification are called instance variables.

Insert picture description here

1.1, the difference between class variables and instance variables

  • Instance variables are allocated to the heap memory after the object is created, and the instance variables belong to a specific object. When an object is created, the instance variable appears in the heap memory. When the object is garbage collected, the instance variable immediately releases the memory.

For example: we create two objects.

Cell c1 = new Cell(4,5);
Cell c2 = new Cell(5,6);

When creating objects c1, c2, the instance variables (4,5), (5,6) appear in the heap memory. When the objects c1, c2 are garbage collected, the instance variables immediately release the memory.

  • Class variables are stored in the method area, "only one copy", shared by all objects. When the class is loaded, it is immediately stored in the method area. When the class is unloaded, the class variable immediately releases the memory.

Development and application :

  1. Class variables can be directly accessed by the class name. It is recommended to use the full name of the class name in development.

For example: we define an entity class.

public class Student {
	// 实例变量,在创建对象之后,被分配到堆内存中,实例变量属于某个具体的对象
	// 当创建对象,实例变量出现在堆内存中,当对象被垃圾回收,实例变量立即释放内存
	String name;

	// 类变量,被存储在方法区中,"只有一份",被所有对象共享
	static String jtName;

	public void print() {
		System.out.println(this.name);
		System.out.println(jtName);
	}
}

Next time you use static variables jtName, we can directly call directly using the Student class name. At the same time, we can understand that the attribute values ​​of the following two objects are the same.

public class Demo01 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student stu1 = new Student();
		stu1.name = "张三";
		stu1.jtName = "王老师";

		Student stu2 = new Student();

		// 一般直接取类名
		// stu2.jtName = "卢老师";
		Student.jtName = "卢老师";
		System.out.println(stu1.name);// 张三
		System.out.println(stu2.name);// null
		System.out.println(stu1.jtName);// 卢老师
		System.out.println(stu2.jtName);// 卢老师
	}
}

2. Static modified member method (static method/class method)

Static methods : static modified methods belong to class methods and can be called without creating an object. Keywords such as this and super cannot be used in static methods, non-static methods cannot be called, and static member variables and static methods of the class can only be accessed. Static method (class method), when the class is loaded, the static method is immediately loaded into the method area, and the class method can be called directly by the class name.

Instance methods : methods without static modification, instance methods, when an object is created, the instance method is immediately loaded into the method area, and multiple instances share an instance method.

2.1, the difference and conclusion of static method and instance method

  • In the class method, the this keyword cannot be used, and the parameter of calling the method object is not implicit in the class method.
  • Instance methods can directly call static methods, while static methods cannot directly access instance members. Objects must be created and accessed by objects.

Conclusion : The data shared by all objects is defined as a static variable, otherwise it is defined as an instance variable method. There is no access to the instance member in the method and can be defined as a static method.

Development and application :

  1. In the project, the methods in the tool class are usually static.

3. Static static code segment

Syntax description :

  1. JVM executes static static code segments when loading classes, which are often used to initialize static variables.
  2. Static code will only be executed and executed once when the class is loaded.
  3. Static is better than objects.

Development and application :

  1. In development, it is usually used to load static resources, read configuration files and other operations, which are implemented in static code segments.

For example:
we define a tool class.

public class SomeUtil {

	// 默认的无参构造
	public SomeUtil() {
		System.out.println("创建对象!");
	}

	// 静态优于对象
	// 静态代码段 当类被加载,立即被执行,一个类在同一个进程中,只加载一次
	static {
		System.out.println("加载静态资源!");
	}

	// 实例代码段
	{
		System.out.println("实例代码段!");
	}

	public static void do1() {
		System.out.println("do1....");
	}

	public static void do2() {
		System.out.println("do2....");
	}

	public static void do3() {
		System.out.println("do3....");
	}

	public static void main(String[] args) {
		SomeUtil.do1();
		SomeUtil.do2();
		SomeUtil.do3();
		SomeUtil s1 = new SomeUtil();
		SomeUtil s2 = new SomeUtil();
	}
}

Executing the main method, we can clearly see the order of execution according to the output content. The static code segment is executed only once, then the static method is executed, and finally the new object executes the parameterless construction and instance code segment, and new is executed once at a time. At the same time, we can draw our conclusion: static is better than objects.
Insert picture description here

4. Static inner class

Syntax description:

  1. The static inner class can be instantiated without relying on the instance object of the outer class, while the inner class needs to be instantiated after the outer class is instantiated.
  2. The static inner class cannot access the ordinary variables of the outer class, but can only access the static member variables and static methods of the outer class.

Seven, final modifier

Syntax description :

  1. The final class cannot be inherited.
  2. The final method cannot be overridden.
  3. The final modified variable is a constant.

Development and application :

  1. In development, use final to define the data dictionary.

For example: In the following Card class, we define a data dictionary for the output and query of the main function.

Remarks : Data dictionary refers to the definition and description of data items, data structure, data flow, data storage, processing logic, etc. Its purpose is to give a detailed description of each element in the data flow chart. Use the data dictionary as Simple modeling project. In short, a data dictionary is a collection of information describing data and a collection of definitions for all data elements used in the system.

public class Card {

	// 开发中,使用final定义数据字典。
	public static final int SPADE = 1;
	public static final int HEART = 2;

	public static final int BLACK = 5;
	public static final int FLOWER = 6;

	public static final int THREE = 0;
	public static final int EIGHT = 5;
	public static final int JACK = 8;
	public static final int QUEEN = 9;
	public static final int KING = 10;
	public static final int ACE = 11;
	public static final int DUCE = 12;
	public static final int JOKER = 13;

	private int suit;
	private int num;

	public Card() {
	}

	public Card(int suit, int num) {
		this.suit = suit;
		this.num = num;
	}

	public int getSuit() {
		return suit;
	}

	public void setSuit(int suit) {
		this.suit = suit;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public static void main(String[] args) {
		Card card = new Card(Card.HEART, Card.THREE);
		System.out.println(card.getNum());
	}
}

Eight, abstract modifier

Syntax description :

  1. Abstract, you can modify classes and modify methods.

Abstract class :

  • The meaning of abstract classes is to be inherited.
  • Abstract classes cannot create objects.
  • abstract cannot be used with final.

Abstract method :

  • Abstract methods, only definitions are not implemented.
  • If there are abstract methods in a class, this class must be an abstract class.
  • There can be no abstract methods in an abstract class.
  • The subclass of the abstract class must implement all the abstract methods in the parent class.

Development and application :

  1. An abstract class can have both default implementation methods and non-implemented methods.
  2. Interface adapter-use subclasses to implement methods in the interface.

Nine, interface (special abstract class)

Syntax description :

  1. The methods in the special abstract class interface are all abstract methods. The variables in the interface are all static constants.
  2. Use the interface keyword to define the interface.
  3. Use the implements keyword to implement the interface.
  4. The class implements the interface and must implement all the methods in the interface.
public interface MyInterface {
	// 接口是高一级别的抽象。不能被实例化,所以只能定义常量
	// 定义了变量需要实例化,赋值才能使用,跟接口违背
	// 特殊的抽象类 接口中的方法都是抽象方法 接口中的变量都是静态常量
	int I = 10;

	// 如果类中所有的方法都是抽象方法,使用接口
	void method1();

	void method2();
}
import java.io.Serializable;

/**
 * 其实适配器只是一个类,它实现了某种接口,提供了方法体。 
 * 这样,再用到这个接口时,可以直接继承适配器,这样就不需要把接口中的每一个方法再填充一遍了。
 * 只需要在这个类中复写一下需要用的方法。这样简单,方便。
 * 
 * @author bailu
 *
 */
public class MyImpClass implements MyInterface, Serializable {
	
	// Serializable序列化
	private static final long serialVersionUID = 1L;

	// 重写接口的方法——适配器,
	@Override
	public void method1() {
		System.out.println(I);

	}

	@Override
	public void method2() {
	}
}

Development and application :

  1. If all methods in the class are abstract methods, use interfaces.

1. The difference between abstract class and interface

  • In an abstract class, you can define abstract methods and non-abstract methods. In the interface, all methods are abstract methods.
  • A class can only inherit one abstract class. A class can implement multiple interfaces, and multiple interfaces are separated by commas.

For example: the following class not only implements the interface MyInterface, but also implements Serializable serialization.

import java.io.Serializable;

/**
 - 其实适配器只是一个类,它实现了某种接口,提供了方法体。 
 - 这样,再用到这个接口时,可以直接继承适配器,这样就不需要把接口中的每一个方法再填充一遍了。
 - 只需要在这个类中复写一下需要用的方法。这样简单,方便。
 - 
 - @author bailu
 -  */
public class MyImpClass implements MyInterface, Serializable {
	
	// Serializable序列化
	private static final long serialVersionUID = 1L;

	// 重写接口的方法——适配器,
	@Override
	public void method1() {
		System.out.println(I);

	}

	@Override
	public void method2() {
	}
}
  • Abstract classes can also be inherited, but only single inheritance is supported. Interfaces can also be inherited, and one interface can inherit multiple interfaces.

Development and application :

  1. The interface is used to formulate standards or specifications.

  2. It can reduce the coupling between components and expand the functions of components.

  3. Reflects the opening and closing principles in the design pattern.

2. What is an adapter?

The adapter is just a class, which implements the interface and provides the method body. When you use this interface again, you can directly inherit the adapter, so you don't need to fill in every method in the interface again, you only need to copy the methods you need in this class. The interface well reflects the opening and closing principles in the design pattern.

For example, when we build an online mall system, we need to call a third-party payment-bank or Alipay's payment interface. We need a third party to provide us with an interface, which defines an abstract method and a method to implement the interface-adapter, we complete the payment by calling the method in the adapter.

ZsBankInter obj = 获取实现类对象;
obj.send();
京东、淘宝
银行接口ZsBankInter  
send() 
类
class DoSend implements ZsBankInter{
  	send()具体的方法
}

to sum up

Modifiers have four use cases in the Java language: member variables, member methods, code blocks, and inner classes. Above we have summarized 11 common modifiers encountered in the daily development process, and understood and cleared these common modifier syntax descriptions and common development application cases from the most basic bottom layer and principles. There are still many specific contents, so this article will not list them one by one for the time being, and it will be completed according to development needs in the future.

Insert picture description here


Thank you for your support. I am Bailu, a programmer who works tirelessly. I hope this post can help everyone, and welcome everyone's one-click three-connection! If you have any questions, suggestions or supplements, you can leave a message at the bottom of the post to help more people!
More information WeChat search public accountWDeerCode code circle

Guess you like

Origin blog.csdn.net/qq_22695001/article/details/107664196