Java Basics--Encapsulation

foreword

The Java language is a pure object-oriented programming language, so it has the characteristics of encapsulation, inheritance, and polymorphism. What we will learn today is the encapsulation feature.

Before learning, we should know what is encapsulation, why is encapsulation, and how to implement encapsulation

In Java, encapsulation is an object-oriented programming concept used to encapsulate related data and behavior into a single entity, called a class. By using access modifiers (such as public, private, protected) to control the visibility of members of the class, so as to realize the restriction of data hiding and access.

In Java, the main purpose of encapsulation is to protect the internal state of an object from direct external access and modification, and only allow data to be manipulated through defined methods. Here are a few reasons and benefits of encapsulation:

  1. Data Hiding : Encapsulation prevents direct external access and modification of an object's internal state by declaring data as private. Only public methods are provided to control access to data, which ensures data integrity and security.
  2. Information isolation : Encapsulation encapsulates data and operations inside the class, hiding specific implementation details from external code. In this way, the external code only needs to care about how to use the public method to interact with the object without knowing the internal implementation logic, which reduces the complexity of the code.
  3. Code reuse : Encapsulation makes code more modular and maintainable. Code reusability can be improved by encapsulating related data and methods in a single class. Other code can use the encapsulated class by creating objects and calling public methods without concern for specific implementation details.
  4. Flexibility and extensibility : Encapsulation provides a kind of independence, so that the internal implementation of the class can be freely modified without affecting the external code. In this way, the flexibility and scalability of the system can be enhanced, and it is convenient to modify, optimize or extend the functions of the class.

In short, encapsulation is an important feature of Java object-oriented programming. By hiding and restricting access to data, it provides a clear interface and information isolation, which brings benefits such as data security, code reusability, and system flexibility.

To achieve class encapsulation, you can follow the steps below:

  1. Make the properties of the class private: When defining a class, use the private keyword to modify the properties of the class, that is, to set the property as a private (private) access right. This prevents external code from directly accessing the property.
    public class MyClass {
        private int myPrivateVariable; // 私有属性
    }
    
  2. Provide public setter and getter methods: Set and get the value of private properties through public (public) methods. The setter method is used to set the value of the property, and the getter method is used to obtain the value of the property, and these two methods usually start with "set" and "get", followed by the capitalized form of the property name.
    public class MyClass {
        private int myPrivateVariable; // 私有属性
    
        public void setMyPrivateVariable(int value) {
            myPrivateVariable = value;
        }
    
        public int getMyPrivateVariable() {
            return myPrivateVariable;
        }
    }
    
  3. Access properties through setter and getter methods: External code needs to set and get the value of the property by calling the object's public methods (setter and getter). This enables indirect access and manipulation of private properties.
    public class Main {
        public static void main(String[] args) {
            MyClass obj = new MyClass();
            obj.setMyPrivateVariable(10); // 通过setter方法设置属性值
            int value = obj.getMyPrivateVariable(); // 通过getter方法获取属性值
            System.out.println(value); // 输出: 10
        }
    }
    

Through the above steps, we privatize the property and provide access to the property through the public setter and getter methods, realizing the encapsulation of the class. This ensures that access to attributes is restricted, while providing a mechanism to control data access and keep data secure.

this keyword

In Java development, when member variables and local variables have the same name problem, you can use the this keyword to distinguish them. The main functions of the this keyword are as follows:

  1. Call the properties in this class: By using the this keyword, you can refer to the member variables of the current object. In this way, member variables with the same name can be accessed inside the method or constructor instead of local variables.
    public class MyClass {
        private int myVariable;
    
        public void setMyVariable(int myVariable) {
            this.myVariable = myVariable; // 使用this关键字访问成员变量
        }
    }
    
  2. Call member methods: use this keyword to call other member methods of the current object. Through the form of this.methodName(), other methods of the same object can be called inside a member method.
    public class MyClass {
        public void method1() {
            System.out.println("这是方法1");
        }
    
        public void method2() {
            this.method1(); // 使用this关键字调用成员方法
            System.out.println("这是方法2");
        }
    }
    
  3. Call the constructor of this class: Inside the constructor, use the this keyword to call other constructors of this class. This enables overloading of constructors and code reuse.
    class Student {
    	private String name;
    	private int age;
    	public Student () {
    		System.out.println("实例化了一个新的Student对象。");
    	}
    	public Student (String name,int age) {
    		this();                  // 调用无参的构造方法
    		this.name = name;
    	    this.age = age;
    		}
    		public String read(){
    	        return "我是:"+name+",年龄:"+age;
    		}
    	}
    	public class myclass { 
    		public static void main(String[] args) {
    		    Student stu = new Student ("张三",18); // 实例化 Student对象
    	         System.out.println(stu.read());
    		}
    	}

When using the this keyword to call the constructor of a class, you need to pay attention to the following points:

  1. You can only use this in the constructor to call other constructors: the this keyword can only be used inside the constructor and is used to call other constructors of the same class. It cannot call constructors through this in ordinary member methods.
  2. In the construction method, the statement using this to call the construction method must be on the first line: If this is used in a construction method to call another construction method, then the this calling statement must appear in the first line of code of the construction method. This is because the constructor method will first execute the called constructor method when creating an object, so ensuring that the call statement is in the first line can avoid logic errors.
  3. You cannot use this to call each other in two constructors of a class.

static block

I talked about static variables in the previous article. If students don’t understand something, you can go back and look again. This is the portal: Java Basics--Variable Types

In Java, the content of a static code block is loaded when the class is first used, and only once. They are executed during class loading, taking precedence over other code blocks and constructors.

Static code blocks are used to initialize static variables or perform operations that only need to be performed once, so they are usually used for some global initialization work.

The construction code block is executed every time an object is created, before the construction method. It is mainly used to avoid repeated code logic in multiple construction methods, and can assign values ​​​​to instance variables before object creation.

Overall, the order of execution is:

  1. Static code block (executed when the class is loaded, only once)
  2. Construction code block (executed every time an object is created, before the construction method)
  3. Construction method

It should be noted that when there is an inheritance relationship, the static code block of the parent class will be executed before the static code block of the subclass; while the construction code block and the construction method will be executed sequentially in the order in which the object is actually created.

Next, learn the use of static code blocks through a case.

public class myclass {
    private static int staticVariable; // 静态变量

    private int instanceVariable; // 实例变量

    // 静态代码块
    static {
        staticVariable = 10;
        System.out.println("静态代码块被执行");
    }

    // 构造代码块
    {
        instanceVariable = 20;
        System.out.println("构造代码块被执行");
    }

    // 构造方法
    public myclass() {
        System.out.println("构造方法被执行");
    }

    public static void main(String[] args) {
        myclass example1 = new myclass();
        myclass example2 = new myclass();
    }
}

operation result:

静态代码块被执行
构造代码块被执行
构造方法被执行
构造代码块被执行
构造方法被执行

As can be seen from the output, the static code block is executed when the class is used for the first time, only once. The construction code block is executed every time an object is created, before the construction method is executed.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132290897
Recommended