The fourth chapter is object-oriented programming

Three main lines of Java object-oriented learning: (Chapter 4-6):

1.Java classes and class members: properties, methods and constructors; Code block, inner class
2. Three characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstraction)
3. Other keywords: this, super, static, final, abstract, interface, package, import, etc

Tip: "focus on the big, start with the small"

preface

1, Process oriented and object-oriented

Process oriented: it emphasizes the functional behavior, taking the function as the minimum unit and considering how to do it.

 * ① Open the refrigerator door
 * ② Lift the elephant and stuff it into the fridge
 * ② Close the refrigerator door

Object oriented: emphasize the objects with functions, take the class / object as the minimum unit, and consider who will do it.

 
 * people{
 * 		open(Refrigerator){
 * 			Refrigerator.Open();
 * 		}
 * 
 * 		lift(elephant){
 * 			elephant.get into(Refrigerator);
 * 		}
 * 
 * 		close(Refrigerator){
 * 			Refrigerator.close();
 * 		}
 * 
 * }
 * 
 * 
 * Refrigerator{
 * 		Open(){}
 * 		close(){}
 * }
 * 
 * elephant{
 * 		get into(Refrigerator){
 * 		}
 * }

2, Two elements of object orientation:

  • Class: the description of a class of things, which is an abstract and conceptual definition
  • Object: it refers to each individual of this kind of thing that actually exists, so it is also called instance
  • The focus of object-oriented programming is the design of classes

  • A design class is a member of a design class

3, Creation and use of classes and objects

1. A design class is actually a member of a design class

Attribute = member variable = field = field, field
Method = member method = function = method
Object to create class = instantiation of class = instantiation of class

2. Use of classes and objects (implementation of object-oriented idea):

  • 1. Create a class and design the members of the class
  • 2. Create class objects
  • 3. Call the structure of the object through "object. Attribute" or "object. Method"

3. If you create multiple objects of a class, each object has a set of class properties independently. (non static)

  • This means that if we modify attribute a of one object, the value of attribute a of another object will not be affected.

4. Memory parsing of objects

Code example:

//Test class
public class PersonTest {
	public static void main(String[] args) {
		//2. Create the object of Person class
		Person p1 = new Person();
		//Scanner scanner = new Scanner(System.in);
		
		//Structure of calling object: attribute and method
		//Calling property: "object. Property"
		p1.name = "Tom";
		p1.isMale = true;
		System.out.println(p1.name);
		
		//Calling method: "object. Method"
		p1.eat();
		p1.sleep();
		p1.talk("Chinese");
		
		//*******************************
		Person p2 = new Person();
		System.out.println(p2.name);//null
		System.out.println(p2.isMale);
		//*******************************
		//Assigning the object address value saved by the p1 variable to p3 causes p1 and p3 to point to the same object entity in the heap space.
		Person p3 = p1;
		System.out.println(p3.name);//Tom
		
		p3.age = 10;
		System.out.println(p1.age);//10
		
	}
}

//1. Create a class and design the members of the class
class Person{
	
	//attribute
	String name;
	int age = 1;
	boolean isMale;
	
	//method
	public void eat(){
		System.out.println("People can eat");
	}
	
	public void sleep(){
		System.out.println("People can sleep");
	}
	
	public void talk(String language){
		System.out.println("People can talk,Used are:" + language);
	}
	
}

4, One of the members of the class: properties

Attribute (member variable) vs local variable

1. Similarities:

    1.1  Define the format of the variable: data type variable name = Variable value
	1.2 Declaration before use
	1.3 Variables have their corresponding scopes  

2. Differences:

2.1 Different positions declared in the class
    Attribute: a pair defined directly in a class{}within
    Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors
2.2 Differences about permission modifiers
    Attribute: when declaring an attribute, you can specify its permission and use the permission modifier.
	Common permission modifiers: private,public,Default protected  --->Encapsulation
	At present, when you declare properties, you can use the default.
    Local variable: permission modifier cannot be used.
2.3 Default initialization value:
    Attribute: the attribute of a class has a default initialization value according to its type.
	Integer( byte,short,int,long): 0
	Floating point type( float,double): 0.0
	Character type( char): 0  (or'\u0000')
	Boolean type( boolean): false  
	Reference data type (class, array, interface): null
    Local variable: no default initialization value.
    This means that we must explicitly assign values before calling local variables.
	In particular: when the formal parameter is called, we can assign a value
2.4 Location loaded in memory:
	Attributes: loading into heap space (not static)
	Local variables: loading into stack space

Code example

public class UserTest {
	
	public static void main(String[] args) {
		User u1 = new User();
		System.out.println(u1.name);
		System.out.println(u1.age);
		System.out.println(u1.isMale);
		
		u1.talk("Korean");
		
		u1.eat();
		
	}
}

class User{
	//Attribute (or member variable)
	String name;
	public int age;
	boolean isMale;
	
	
	public void talk(String language){//language: formal parameter, which is also a local variable
		System.out.println("We use" + language + "Communicate");
		
	}
	
	public void eat(){
		String food = "Flapjack";//local variable
		System.out.println("Northerners like to eat:" + food);
	}
	
}

5, One of the members of class: method

Method: describe the function that the class should have.
For example: Math class: sqrt()\random()
Scanner class: nextXxx()
Arrays class: sort() \ binarySearch() \ toString() \ equals() \

1. Examples:

  • public void eat(){}
  • public void sleep(int hour){}
  • public String getName(){}
  • public String getNation(String nation){}

2. Statement of method:

Permission modifier return value type method name(parameter list ){
   							Method body
 			  }
  • Note: static, final and abstract are used to modify the method, which will be discussed later.

3. Description:

	3.1 About permission modifiers: the permission modifiers of the default method are used first public
		Java There are four types of authority modifiers specified: private,public,Default protected  -->More details on encapsulation 
	3.2 Return value type: with return value  vs no return value
		3.2.1  If a method has a return value, the type of the return value must be specified when the method is declared. At the same time, in the method, you need to use
               return Keyword to return a variable or constant of the specified type:“ return Data ".
			   If the method does not return a value, when declaring the method, use void To show. Usually, in methods that do not return a value, you do not need to
               use return.However, if used, only“ return;"Means to end this method. 
		3.2.2 Do we define whether a method should have a return value?
			① Title Requirements
			② Based on experience: specific analysis of specific problems 
         3.3 Method name: it belongs to the identifier and follows the rules and specifications of the identifier, "see the meaning of the name"      
  3.4 Formal parameter list: method can declare 0, 1, or more formal parameters.
      3.4.1 Format: data type 1 parameter 1,Data type 2 parameter 2,...
      
      3.4.2 When we define methods, should we define formal parameters?
      		① Title Requirements
      		② Based on experience: specific analysis of specific problems      
      3.5 Method body: the embodiment of method function. 		

4. Use of return keyword:

1.Scope of use: used in the method body
2.effect:    ① End method
           ② For methods with return value types, use"return data"Method returns the desired data.
3.Note: return You cannot declare an execution statement after a keyword.

5. When using the method, you can call the property or method of the current class

	Special: method A Method called again in A:Recursive method.
   Method cannot be defined.

Code example:

public class CustomerTest {
	public static void main(String[] args) {
		
		Customer cust1 = new Customer();
		
		cust1.eat();
		
		//Test whether formal parameters need to be set
//		int[] arr = new int[]{3,4,5,2,5};
//		cust1.sort();
		
		cust1.sleep(8);
		
	}
}

//Customer class
class Customer{
	
	//attribute
	String name;
	int age;
	boolean isMale;
	
	//method
	public void eat(){
		System.out.println("Customers eat");
		return;
		//You cannot declare an expression after return
//		System.out.println("hello");
	}
	
	public void sleep(int hour){
		System.out.println("rest" + hour + "Hours");
		
		eat();
//		sleep(10);
	}
	
	public String getName(){
		
		if(age > 18){
			return name;
			
		}else{
			return "Tom";
		}
	}
	
	public String getNation(String nation){
		String info = "My nationality is:" + nation;
		return info;
	}
	
	//Experience the problem of whether formal parameters need to be set
//	public void sort(int[] arr){
//		
//	}
//	public void sort(){
//		int[] arr = new int[]{3,4,5,2,5,63,2,5};
//		//. . . . 
//	}
	
	public void info(){
		//FALSE
//		public void swim(){
//			
//		}
		
	}
}

6. Practice

Exercise 1

public class Person {
	
	String name;
	int age;
	/**
	 * sex:1 Indicates that it is male
	 * sex:0 Indicates a woman
	 */
	int sex;
	
	public void study(){
		System.out.println("studying");
	}
	
	public void showAge(){
		System.out.println("age:" + age);
	}
	
	public int addAge(int i){
		age += i;
		return age;
	}
}
/*
 * requirement:
 * (1)Create an object of the Person class, set the name, age and sex properties of the object, and call the study method,
 * Output the string "studying", call the showAge() method to display the age value,
 * Call the addAge() method to increase the age attribute value of the object by 2 years.
 * (2)Create a second object and perform the above operations to experience the relationship between different objects of the same class.
 * 
 * 
 */
public class PersonTest {
	public static void main(String[] args) {
		Person p1 = new Person();
		
		p1.name = "Tom";
		p1.age = 18;
		p1.sex = 1;
		
		p1.study();
		
		p1.showAge();
		
		int newAge = p1.addAge(2);
		System.out.println(p1.name + "The new age is:" + newAge);
		
		System.out.println(p1.age);//20
		
		//*************************
		Person p2 = new Person();
		p2.showAge();//0
		p2.addAge(10);
		p2.showAge();//10
		
		p1.showAge();
		
	}
}

Exercise 2

package com.atguigu.exer;
/*
 * 4. Object array Title:
Class Student is defined, which contains three attributes: Student number(int), grade state(int), and grade score(int).
 Create 20 student objects with student numbers from 1 to 20. Grades and grades are determined by random numbers.
Question 1: print out the student information of grade 3 (state value is 3).
Question 2: use bubble sorting to sort students' grades and traverse all student information

Tips:
1) Generate random number: math Random(), return value type double;  
2) Rounding: math Round (double D), return value type long.
 * 
 * 
 * This code is for studenttest Improvement of Java: encapsulate the function of operating array into method.
 * 
 */
public class StudentTest1 {
	public static void main(String[] args) {
		
		//Declare an array of Student type
		Student1[] stus = new Student1[20];  
		
		for(int i = 0;i < stus.length;i++){
			//Assign values to array elements
			stus[i] = new Student1();
			//Assign a value to the property of the Student object
			stus[i].number = (i + 1);
			//Grade: [1,6]
			stus[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
			//Score: [0100]
			stus[i].score = (int)(Math.random() * (100 - 0 + 1));
		}
		
		StudentTest1 test = new StudentTest1();
		
		//Traverse student array
		test.print(stus);
		
		System.out.println("********************");
		
		//Question 1: print out the student information of grade 3 (state value is 3).
		test.searchState(stus, 3);
		
		System.out.println("********************");
		
		//Question 2: use bubble sorting to sort students' grades and traverse all student information
		test.sort(stus);
		
		//Traverse student array
		test.print(stus);
		
	}
	
	/**
	 * 
	 * @Description  Operation of traversing Student1 [] array
	 * @author shkstart
	 * @date 2019 At 5:10:19 pm on January 15
	 * @param stus
	 */
	public void print(Student1[] stus){
		for(int i = 0;i <stus.length;i++){
		 ·
		}
	}
	/**
	 * 
	 * @Description Find the student information of the specified grade in the student array
	 * @author shkstart
	 * @date 2019 5:08:08 PM, January 15
	 * @param stus Array to find
	 * @param state Grade you are looking for
	 */
	public void searchState(Student1[] stus,int state){
		for(int i = 0;i <stus.length;i++){
			if(stus[i].state == state){
				System.out.println(stus[i].info());
			}
		}
	}
	
	/**
	 * 
	 * @Description Sort Student1 array
	 * @author shkstart
	 * @date 2019 January 15, 2005 5:09:46 PM
	 * @param stus
	 */
	public void sort(Student1[] stus){
		for(int i = 0;i < stus.length - 1;i++){
			for(int j = 0;j < stus.length - 1 - i;j++){
				if(stus[j].score > stus[j + 1].score){
					//If you need to change the order, exchange the elements of the array: Student object!!!
					Student1 temp = stus[j];
					stus[j] = stus[j + 1];
					stus[j + 1] = temp;
				}
			}
		}
	}
	
	
}

class Student1{
	int number;//Student number
	int state;//grade
	int score;//achievement
	
	//Method of displaying student information
	public String info(){
		return "Student number:" + number + ",Grade:" + state + ",Achievements:" + score;
	}
	
}


Summary: understand "all things are objects" and anonymous objects

1. In the category of Java language, we all encapsulate functions and structures into classes, and call specific function structures through class instantiation

  • >Scanner,String etc.
    
  •  >File: File
    
  • >Network resources: URL
    

2. When it comes to the interaction between the Java language and the front-end Html and back-end databases, the front and back-end structures are embodied as classes and objects at the Java level.

2, Description of memory parsing

  • 1. Variables of reference type can only store two types of values: null or address value (including the type of variable)
  • 3, Use of anonymous objects
  • 1. Understanding: the object we created is not explicitly assigned to a variable name. Is an anonymous object
  • 2. Features: anonymous objects can only be called once.
  • 3. Usage: as follows:
public class InstanceTest {
	public static void main(String[] args) {
		Phone p = new Phone();
//		p = null;
		System.out.println(p);
		
		p.sendEmail();
		p.playGame();
		
		
		//Anonymous object
//		new Phone().sendEmail();
//		new Phone().playGame();
		
		new Phone().price = 1999;
		new Phone().showPrice();//0.0
		
		//**********************************
		PhoneMall mall = new PhoneMall();
//		mall.show(p);
		//Use of anonymous objects
		mall.show(new Phone());
		
	}
}

class PhoneMall{
	
	
	public void show(Phone phone){
		phone.sendEmail();
		phone.playGame();
	}
	
}


class Phone{
	double price;//Price
	
	public void sendEmail(){
		System.out.println("Send mail");
	}
	
	public void playGame(){
		System.out.println("play a game");
	}
	
	public void showPrice(){
		System.out.println("The price of mobile phone is:" + price);
	}
	
}

Keywords: Java Back-end

Added by webtech123 on Sat, 29 Jan 2022 15:20:47 +0200