Encapsulation of this keyword and code

this keyword

1.this represents an object, which can appear in instance methods and construction methods, but not in class methods;
2. Use this in the construction method. This represents the object created by the construction method
3. Use this in the instance method, which represents the current object calling the method

encapsulation

  1. Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being randomly accessed by the code defined by the external class. The main function of encapsulation is that we can modify our implementation code without modifying the program fragments that call our code.

Steps to implement Java encapsulation

1. Attribute privatization;

Modify the attribute with private. If the attribute is set to private, it can only be accessed by this class, and can not be accessed by other classes

2. Provide getter and setter methods externally as the entry to access private properties

Any class that wants to access private member variables in the class must pass through these getter and setter methods.

  1. get method: used to read data
    public return value type get + initial capital of attribute name (no parameter){
    return xxx;
    }
  2. set method: used to modify data
    Public void set + initial capitalization of attribute name (with one parameter){
    xxx = parameter;
    }
public class EncapTest{
 //1. Property privatization
   private String name;
   private String idNum;
   private int age;
 //Provide getter and setter methods externally
   public int getAge(){
      return age;
   }
 
   public String getName(){
      return name;
   }
 
   public String getIdNum(){
      return idNum;
   }
 
   public void setAge( int newAge){
      age = newAge;
   }
 
   public void setName(String newName){
      name = newName;
   }
 
   public void setIdNum( String newId){
      idNum = newId;
   }
}

When accessing:

public class RunEncap{
   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");
 
      System.out.print("Name : " + encap.getName()+ 
                             " Age : "+ encap.getAge());
    }
}
//The operation results are as follows:
Name : James Age : 20

Summary:

  1. this is a reference that holds the memory address to itself
  2. this. Most of them can be omitted, but they cannot be omitted when the real column variable and the global variable have the same name;
  3. this() syntax can only appear in the first line of the constructor, indicating that the current constructor calls other constructors of this class for code reuse;
  4. One copy of an object is an instance variable, and one copy of all objects is a static variable;

Code column:

package day1;
/*Title:
 * Define a date class that can represent year, month and day
 * If the parameterless construction method is called, the default creation date is January 1, 1970
 * You can also call a constructor with parameters to create a date object
 * In the future, develop the habit of code encapsulation
 * */
	class Date{//Encapsulation: privatize the attributes first, and provide get and set methods externally
		private int year;
		private int month;
		private int day;
		//1. Nonparametric construction method
		public Date() {
			 this.year=1997;
			 this.month=1;
			 this.day=1;
		}
		//2. Parametric construction method
		public Date(int year, int month, int day) {
			super();
			this.year = year;
			this.month = month;
			this.day = day;
		}
		
		//3.set and get
		public int getYear() {
			return year;
		}
		public void setYear(int year) {
			this.year = year;
		}
		public int getMonth() {
			return month;
		}
		public void setMonth(int month) {
			this.month = month;
		}
		public int getDay() {
			return day;
		}
		public void setDay(int day) {
			this.day = day;
		}
		//Provides a way to print dates
		public void  dayin(){
			System.out.println(year+"year"+month+"month"+day+"day");
		}
	}
//Main function, i.e. entry
	public class Book{
	public static void main(String[] args) {
		 //Call parameterless constructor
		Date a1=new Date();
		a1.dayin();
		//Call the constructor with parameters
		Date a2=new Date(2021,10,5);
		a2.dayin();
		}
	}

Contents contained in the class body currently studied:

1. Instance variables and methods
2. Static variables and static methods
3. Construction method
4. Method{
Local variables;
}
4. Static code block
5. Example code block

The general order of writing code at present:

  1. Classes and main methods of eclips
  2. Customize a class, which includes: first write the attribute (customize each instance or static variable), the construction method includes writing both without parameters and with parameters, encapsulation (first private each attribute, then provide set and get methods externally, and provide access entry), and then customize the instance or static method;
  3. Create an object in the main class (or main method)
  4. Object calls instance methods or variables; class name calls static methods or variables
code:
package review;
public class review2 {
	//Static code block
	static{
		System.out.println("stay review2 Execute when class is loaded");
	}//Although this program has two static code blocks, execute this first because the main method in this class is executed first, and the main method loads the review2 class first
	//Class loading is like this: before program execution, all classes that need to be loaded are loaded into the JVM. After loading, the main method will be executed
	public static void main(String[] args) {
		//Call parameterless construction method when creating object
		 Student s=new Student();
		 s.m2();
		 Student.m1();
	}
	
}
	//Student class
	class Student{
		static String job="study";//Static variable
		private String name;
		private int no;//Student number
		//Construction method, no participation and participation
		public Student() {
			//Assuming that the construction method without parameters is called, the default student ID is 216 and the name is Zhang San;
			this("Zhang San",216);//Use this()
		}
		public Student(String name, int no) {
			super();
			this.name = name;
			this.no = no;
		}
		//Encapsulation, set and get methods
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public int getNo() {
			return no;
		}
		public void setNo(int no) {
			this.no = no;
		}
		//Static code block
		static {
			System.out.println("stay Student Execute when class is loaded");
		}
		//Instance code block
		{
			System.out.println("The construction method is executed once, and it is executed once here");
		}
		//Example method
		public void m2() {
			System.out.println(name+"just"+job);
			//Equivalent to below
			/*name Although it is privatized, it can be accessed in this class,
			 * In other classes, you can only access the encapsulated properties in this class through set and get*/
			System.out.println(this.name+"just"+Student.job);
		}
		//Static method
		public static void m1() {
			Student a=new Student();
			System.out.println(a.name+"Have a meal");
			System.out.println(a.name+job);
		}
	}

Posted by rledieu on Sat, 06 Nov 2021 03:21:10 -0700