06 - object oriented upgrade (object oriented)

Posted by binto on Tue, 07 Dec 2021 19:36:06 +0100

Thank you for passing by. I hope the student's notes can give you a trivial reference (1 / 100)
Java object-oriented mind map, [link to the complete Java Architecture]

1, Encapsulate private

1.1 significance:

    Protect or prevent code from being inadvertently damaged, protect member properties, and prevent programs outside the class from accessing and modifying. To access the data of this class, you must use the specified method.

1.2 principle:

    Hide properties and implementation details, provide access to them by public methods, and control access levels.

1.3 steps of packaging:

    1. Use the private keyword to modify member variables.
    2. For the member variables to be accessed, provide a corresponding pair of getXxx methods and setXxx methods.

1.4 meaning of private

    private is a permission modifier that represents the minimum permission
    You can modify member variables and member methods
    Member variables and member methods modified by private can only be accessed in this class

1.5 format of private

    Modify member variables with private
    Provide getXxx method / setXxx method to access member variables
    Others: Shift+Alt+s=get,set method shortcut
code:

package b_XX_JinJi;

public class Demo01_FengZhuang {
	/**
	 * encapsulation
	 * @param args
	 */
	public static void main(String args[]){ 
		/*
		 * // Unreasonable program person per = new person(); Per.name = "Zhang San"; per.age = -30 ;
		 * per.tell() ;
		 */
		Person2 per = new Person2() ;
		per.setName("Zhang San") ; 
		per.setAge(-30) ; 
		per.tell() ;	
	
	}
}

/**
 * @Description: TODO(Unreasonable procedure) 
 * @author: Wang Yuhui
 * @Date: 2021 August 16, 2012 12:07:10 PM
 */
class Person{ 
	private String name ; // Indicate name 
	private int age ; // Indicates age 
	void tell(){ 
		System.out.println("full name:" + name + ";Age:" + age) ; 
		} 
	}

/**
 * @Description: TODO(Reasonable procedure) 
 * Encapsulate all properties and provide setter and getter methods for setting and obtaining operations
 * @author: Wang Yuhui
 * @Date: 2021 August 16, 2012 12:07:10 PM
 */
class Person2{ 
	private String name ; // Indicate name 
	private int age ; // Indicates age 
	
	void tell(){ 
		System.out.println("full name:" + getName() + ";Age:" + getAge()) ; 
		}
	
	public void setName(String str){ 
		name = str ; 
		}
	
	public void setAge(int a){ 
		if(a>0&&a<150) 
			age = a; 
		}
	
	public String getName(){ 
		return name ; 
		}
	
	public int getAge(){ 
		return age ; 
		} 
	}

2, this keyword

    In the foundation of Java, the this keyword is one of the most important concepts. Use this keyword to complete the following operations:
·        Attribute in calling class: this. Member variable name
      · Calling a method or constructor in a class
      · Represents the current object: this represents the reference (address value) of the current object of the class, that is, the reference of the object itself
code:

package b_XX_JinJi;

public class Demo02_This {
	/**
	 * this keyword
	 * @param args
	 */
	public static void main(String args[]){
		Person12 p1 = new Person12("Zhang San",13);
		Person12 p2 = new Person12("Li Si",19);
		p1.say();
		p2.say();
	
		Person12 p3 = new Person12();
		p3.say();
		
	}
}

/**
 * this Refers to the current object
 * @author: Wang Yuhui
 * @Date: 2021 August 16, 2013 3:38:21 PM
 */
class Person12{
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	// Nonparametric construction method
	Person12(){// Set default parameters
		this("Default name",18);
	}

	void say() {
		System.out.println("full name:"+name+",Age:"+age);
	}

	// Full parameter construction method
	Person12(String name,int age){
		this.name = name;
		this.age = age;
	}
	
}

3, Static static

3.1 application:

    Sometimes you want the value of a local variable in a function not to disappear after the function call, but to retain the original value, that is, the storage unit it occupies will not be released. In the next function call, the variable will retain the value at the end of the last function call. In this case, you should specify the local variable as a static local variable.

3.2 function:

    The main function of static is to create domain variables or methods independent of specific objects. Simple understanding:
       The method or variable modified by the static keyword does not need to rely on the object for access. As long as the class is loaded, it can be accessed through the class name. And it will not create multiple copies of data in memory because of multiple creation of objects.
       Statically decorated attributes belong to a class, and there is only one class (method area)
       The attributes decorated by the object belong to the object, and the number of times is unlimited (heap)

3.3 key points:

       1. Static members are loaded and initialized when the class is loaded.
       2. No matter how many objects exist in a class, there is always only one static attribute in memory (it can be understood that all objects are common)
       3. When accessing: static cannot access non static, non static can access static! This is because the execution order is to create classes first. When there are objects, static resources are loaded when creating classes, and non static resources are loaded when creating objects

3.4 example illustration:


code:

package b_XX_JinJi;

public class Demo03_static1 {
	/**
	 * static keyword
	 * @param args
	 */
	public static void main(String[] args) {
		Emp.say1(); // You can use static methods without creating an object
		
		Emp e1 =new Emp("Zhang San","Beijing"); 
		Emp e2 =new Emp("Li Si","Beijing"); 
		Emp e3 =new Emp("Wang Wu","Beijing"); 
		Emp e4 =new Emp("Zhao Si","Beijing"); 
		// Suppose the company moves to Tianjin 
		e1.setRegion("Tianjin");
		e2.setRegion("Tianjin"); 
		e3.setRegion("Tianjin"); 
		e4.setRegion("Tianjin");
		
		e1.say(); 
		e2.say(); 
		e3.say(); 
		e4.say();
		Emp.region = "Beijing"; 
		e3.say();
		
		Emp e =new Emp();
		System.out.println(Emp.count);

	}
}

class Emp {
	private String name;
	static String region;// Same region

	static int count;// Object was called several times

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getRegion() {
		return region;
	}

	public void setRegion(String region) {
		Emp.region = region;
	}

	Emp() {
		count++;
	}

	Emp(String name) {
		this.name = name;
		count++;
	}

	Emp(String name, String region) {
		this.name = name;
		Emp.region = region;
		count++;
	}

	void say() {
		System.out.println("full name:" + name + ",Region:" + region);
	}
	
	// Static method
	static void say1() {
		System.out.println("full name:");
	}
	
	// Non static method
	void say2() {
		System.out.println("full name:" + name + ",Region:" + region);
		say1();
	}
	
}

4, Package

4.1 package introduction

    1. Organize similar or related classes or interfaces in the same package to facilitate the search and use of classes.
    2. Packages are like folders. The names of classes in different packages can be the same. When calling classes with the same class name in two different packages at the same time, the package name should be added to distinguish them. Therefore, the package can avoid name conflicts.
    3. Packages also limit access rights. Only classes with package access rights can access classes in a package.

4.2 usage rules of package

import package name. Class name;

  • Definition of java file in package:
        At the head of the. java file, you must write the package to which the class belongs. Format: package package name;
  • Definition of package:
        It is usually composed of multiple words. The letters of all words are lowercase. Words are separated by. And are generally named "com. Company name. Project name. Module name...".
  • Origin of specification:
    • Due to the object-oriented nature of Java, every java developer can write their own Java Package. In order to ensure the uniqueness of the naming of each Java Package, in the latest Java programming specification, developers are required to add a unique prefix to the package name they define. Because the domain name on the Internet will not be repeated, most developers use the domain name of their company on the Internet as the unique prefix of their packages.
    • For example: com.java.xxx
               - long packages and packages in the same folder do not need to be imported.

5, Code block

    Common code block
       The code blocks that appear in the executed process are called ordinary code blocks.
    Construct code block
       A member code block in a class, which we call a construction code block, is executed every time an object is created and before the construction method.
    Static code block
       The member code block decorated with static in the class is called static code block, which is executed when the class is loaded. A block of code that executes only once each time the program starts to close.
    Synchronous code block
       Learn in the subsequent multithreading technology.
    Interview questions:
       Construction method and execution sequence of construction code block and static code block:
          Static code block -- > construction code block -- > construction method

code:

package b_XX_JinJi;

public class DEmo04_DaiMaKuai {
	/**
	 * Code block
	 * @param args
	 */
	public static void main(String[] args) {
		
		/**
		 * Common code blocks, code blocks written in a sequentially executed code flow
		 */
		{
			int a = 0;
			System.out.println(a);
		}
		
		Person01 p1 = new Person01();
		Person01 p2 = new Person01();
	}
}

// class
class Person01{
	private String name;
	private int age;
	
	/**
	 * Executed every time an object is created, before the construction method.
	 * The difference from the construction method is that no matter which construction method the user calls to create the object, the construction code block must be executed
	 */
	{//Construct code block
		System.out.println("Execute 1 on object creation");
	}
	
	/**
	 * A member code block decorated with static in a class is called a static code block,
	 *  Executed when the class is loaded. A block of code that executes only once each time the program starts to close.
	 */
	static {
		System.out.println("Static code block execution");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
	
	public Person01() {
		System.out.println("Execute 2 on object creation");
	}
	
	public Person01(String name,int age) {
		this.name=name;
		this.age=age;
	}
}

6, main method details

    The main() method has been written to this day:
      public static void main(String args[])
       The meanings of the above parameters are as follows:
      · Public: represents public content, which can be called by all operations
      · Static: indicates that the method is static and can be called directly by the class name. java StaticDemo09
      · void: indicates that there is no return value operation
      · Main: the method name specified by the system. If main is written incorrectly or not, an error will be reported: NoSuchMethodError: main
      · String[] args: string array, which receives parameters

7, Comprehensive exercise

1. Write a Book class to represent books:

       It has attributes: name (title) and number of pages (pageNum). The number of pages cannot be less than 200. Otherwise, an error message will be output and the default value of 200 will be given.
       With methods: set assignment and value taking methods for each attribute. detail, which is used to output the name and pages of each book on the console.
       Write a test class BookTest to test: give the initial value to the properties of the Book object, and call the detail method of the Book object to see if the output is correct

2. Describe the Java students in the class.

       Attributes: name, age, gender, hobbies, company (all: start class),
       Disciplines (both: Java disciplines).
       Thinking: Please combine the static modifier attribute for better class design.

3. Clothes are described by classes. When creating each clothes object, a serial number value needs to be automatically generated.

       Requirements: the serial number of each garment is different and increases by 1 in turn.
Code part:

package ReWu;

/**
 It has attributes: name (title) and number of pages (pageNum). The number of pages cannot be less than 200. Otherwise, an error message will be output and the default value of 200 will be given.
With methods: set assignment and value taking methods for each attribute. detail, which is used to output the name and pages of each book on the console
 * @author: Wang Yuhui
 * @Date: 2021 9:46:45 PM, August 16, 2014
 */
public class Book {
	// attribute
	private String title; //name
	private int pageNum; //the number of pages
	
	// get,set shortcut key settings
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
			this.title = title;
	}
	public int getPageNum() {
		return pageNum;
	}
	public void setPageNum(int pageNum) {//Page number setting
		if(pageNum < 200){
			this.pageNum = 200;
			System.err.println("error message,Change the number of pages to the default value of 200");
			return;
		}
			this.pageNum = pageNum;
		
	}
	 
	Book(){
		this("Default name",200);
	}
	
	Book(String title,int pageNum){
		this.title=title;
		this.pageNum=pageNum;
	}
	
	public void detail() {
		System.out.println("name:"+title+",the number of pages:"+pageNum);
	}
}
package ReWu;
/**
 * Clothes
 * Clothes are described by classes. When each clothes object is created, a sequence number value needs to be automatically generated. 
 * Requirements: the serial number of each garment is different and increases by 1 in turn.
 * @author: Wang Yuhui
 * @Date: 2021 August 16, 2013 10:34:58 PM
 */
public class Clothes {
	
	private int clothId; // Serial number value
	static int number = 1;// The serial number value is automatically increased
	
	Clothes() {// The serial number of each garment is different and increases by 1
		clothId = number;
		number++;
	}

	/**
	 * The set method is not required because the id is automatically generated
	 * @return
	 */
	public int getClothId() {
		return clothId;
	}

	public void say() {
		System.out.println("Serial number value"+clothId);
	}
}
package ReWu;
/**
 	Describe the Java students in the class. Attributes: name, age, gender, hobbies, company (all: start class),
	Disciplines (all Java disciplines)
 * @author: Wang Yuhui
 * @Date: 2021 August 16, 2014 10:14:47 PM
 */
public class Student {
	//attribute
	private String name;// full name
	private int age;// Age
	private int sex;// Gender: 0-male, 1-female
	private String hobby;// hobby
	
	static String company;// company
	static String discipline;// subject
	
	// get,set shortcut key generation
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	public String getHobby() {
		return hobby;
	}
	public void setHobby(String hobby) {
		this.hobby = hobby;
	}
	public static String getCompany() {
		return company;
	}
	public static void setCompany(String company) {
		Student.company = company;
	}
	public static String getDiscipline() {
		return discipline;
	}
	public static void setDiscipline(String discipline) {
		Student.discipline = discipline;
	}
	
	Student(){
		this("Default name",18,0,"run","Let's start the class","java");
	}
	
	Student(String name,int age,int sex,String hobby,String company,String discipline){
		this.name=name;
		this.age=age;
		this.sex=sex;
		this.hobby=hobby;
		Student.company=company;
		Student.discipline=discipline;
	}
	
	public void say() {
		System.out.println("Company:"+company+",Discipline:"+discipline);
	}
}
package ReWu;

public class Task01_BookTest {

	/**
	 * task
	 * @param args
	 */
	public static void main(String[] args) {
		// Task 1
		Book book =new Book();
		book.setTitle("name");
		book.setPageNum(100);
		book.detail();
		 
		// Task 2
		Student student = new Student();
		student.say();
		
		// Task three
		Clothes c1 = new Clothes();
		Clothes c2 = new Clothes();
		Clothes c3 = new Clothes();
		
		System.out.println(c1.getClothId());
		System.out.println(c2.getClothId());
		System.out.println(c3.getClothId());
		
		c1.say();
		c2.say();
		c3.say();	
	}
}

Reference: it's some time since I took notes. Please forgive me if my notes obviously learn from your content. (my memory is very poor. When I first wrote notes, the reference documents may not be complete)
Data download link (notes + code + others): Baidu online disk
Link: https://pan.baidu.com/s/1EXP0qOCQUFexP6fIfMkVlA
Extraction code: 1111
Thank you for reading. I wish you all the best from now on.

Topics: Java IDEA