JavaSE [notes] [object oriented]

Chapter 4 object oriented (Part I)

Process oriented and object oriented

What is the "Object-Oriented" programming idea?

First, explain "thought". First ask you a question: what kind of person do you want to be? Maybe you will answer: I want to be a good person, honor my parents, respect my elders, care for my relatives and friends
You see, this is thought. This is your idea of life, or your principle of life. Being a man has the principle of being a man, and programming also has the principle of programming. These programming principles are programming ideas.

Process oriented (POP) and object oriented (OOP)

  • Object Oriented Programming
  • Process oriented programming
/*
 * 1, Three main lines of learning object-oriented content
 * 1.Java Classes and class members: attributes, methods, constructors, code blocks, internal classes
 * 2.Three characteristics of object-oriented: encapsulation, inheritance, polymorphism, (abstraction)
 * 3.Other keywords: this, super, static, final, abstract, interface, package, import, etc
 * 
 * 2, People put elephants in the fridge
 * 1.Process oriented: it emphasizes the functional behavior, taking the function as the minimum unit and considering how to do it.
 * 
 * ① Open the refrigerator
 * ② Put the elephant in the fridge
 * ③ Close the refrigerator door 
 * 
 * 2.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 the door ();
 * 		}Operation (elephant){
 * 			elephant. Enter (refrigerator);
 * 		}Turn off (refrigerator){
 * 			 Refrigerator. Close the door ();     
 * 		}
 * }
 * 
 * Refrigerator{
 * 		Open the door (){
 * 		}  
 * 		Door closing (){
 * 		}
 * }
 * 
 * Elephant{
 * 		Enter (refrigerator){
 * 		}
 * }
 */

Overview of object-oriented thinking

Programmers have transformed from process oriented executors to object-oriented commanders
Ideas and steps of analyzing problems with object-oriented analysis method:
According to the needs of the problem, select the real-world entity targeted by the problem.
Find the attributes and functions related to solving problems from entities, and these attributes and functions form classes in the conceptual world.
Abstract entities are described in computer language to form the definition of classes in the computer world. That is, with the help of a certain program language, the class is constructed into a data structure that can be recognized and processed by the computer.
Instantiate a class into an object in the computer world. Object is the ultimate tool to solve problems in the computer world.

Classes and objects

  • 3, Two elements of object orientation:
  • Class: the description of a class of things, which is an abstract and conceptual definition
    *Object: it is each individual of such things that actually exist, so it is also called instance.
    • Can be understood as: class = abstract concept of people; Object = a real person
  • Object oriented programming is the key point;
  • A design class is actually a member of a design class.

Java classes and class members

Real world organisms, from whales to ants, are made up of the most basic cells. Similarly, the Java code world is composed of many classes with different functions.
What is the real world made up of cells? Nucleus, cytoplasm,... So is the class used to describe things in Java. Common class members are:

Attribute: the member variable in the corresponding class
Behavior: member methods in corresponding classes

Creation and use of classes and objects

* 1, A design class is actually a member of a design class
 * Field = attribute = Member variable = Fields and fields
 * Method = (member)method = function 
 * 
 * Create class = Class instantiation = Instantiation class
 * 
 * two.Use of classes and objects(Implementation of object-oriented thought)
 * 1.Create a class and design the members of the class
 * 2.Create an object of class
 * 3.Through object.Property or object.Method '' calls the structure of the object
 * 3, If you create multiple objects of a class, each object has a set of class properties independently.(wrong static of)
 * 	  signify:If we modify the properties of an object a,Does not affect another object property a Value of.
 */
//Test class
public class PersonTest {
	public static void main(String[] args) {
		//2. Create the object of Person class
		//Create object syntax: class name object name = new class name ();
		Person p1 = new Person();
		//Scanner scan = new Scanner(System.in);
		
		//Structure of calling class: attribute and method
		//Calling property: "object. Property"
		p1.name = "Tom";
		p1.age = 25;
		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 an object entity in the heap space.
		Person p3 = p1;
		System.out.println(p3.name);
		
		p3.age = 10;
		System.out.println(p1.age); //10
	}
}
/*
 * Syntax format of class:
 * Modifier class name{
 * 		Attribute declaration;
 * 		Method statement;
 * }
 * Description: modifier public: the class can be accessed arbitrarily. The body of the class should be enclosed with {}
 */
//1. Create a class and design the members of the class
class Person{
	
	//Attribute: the member variable in the corresponding class
	String name;
	int age;
	boolean isMale;
	
	//Method: the member method in the corresponding class
	public void eat(){
		System.out.println("having dinner");
	}
	
	public void sleep(){
		System.out.println("sleep");
	}
	
	public void talk(String language){
		System.out.println("People can speak by:" + language);
	}
}

Object creation and usage: memory parsing

  • Heap, the only purpose of this memory area is to store object instances. Almost all object instances allocate memory here. This is described in the Java virtual machine specification: all object instances and arrays should be allocated on the heap.
  • Generally speaking, Stack refers to virtual machine Stack. The virtual machine Stack is used to store local variables, etc. The local variable table stores various basic data types (boolean, byte, char, short, int, float, long, double) with known length during compilation, and object reference (reference type, which is not equivalent to the object itself and is the first address of the object in heap memory). Method is automatically released after execution.
  • The method area is used to store class information, constants, static variables, code compiled by the real-time compiler and other data that have been loaded by the virtual machine.

Case 1

Person p1= newPerson();
p1.name = "Tom";
p1.isMale = true;
Person p2 = new Person();
sysout(p2.name);//null
Person p3 = p1;
p3.age = 10;

Case 2

Person p1= newPerson();
p1.name = "Hu Limin";
p1.age = 23;
Person p2 = new Person();
p2.age = 10;

One of the members of the class: properties

/*

  • Use of properties in class
  • Properties (member variables) vs local variable
  • 1. Similarities:
  •  1.1 Defines 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 The positions declared in the class are different
    
  •  attribute:Directly defined in a pair of classes{}within
    
  •  local variable:Declare variables inside methods, method parameters, constructor parameters, and constructors
    
  •  2.2 Differences about permission modifiers
    
  •  attribute:When declaring attributes, you can specify their permissions and use permission modifiers.
    
  •  	Common permission modifiers:private,public,Default protected
    
  •  	At present, when declaring attributes, you can use the default.
    
  •  local variable:Permission modifiers are not allowed.
    
  •  2.3 Default initialization value:
    
  •  attribute:Class has default initialization values according to its type.
    
  •  	integer(byte,short,int,long):0
    
  •  	float (float,double):0.0
    
  •  	character(char):0(or'\u0000')
    
  •  	Boolean type(boolean):false
    
  •  	Reference data type(Class, array, interface):null
    
  •  local variable:There is no default initialization value
    
  •  	signify:Before calling a local variable, you must explicitly assign a value.
    
  •  	Especially:Formal parameter when called,Assignment is enough. Example, 45 lines
    
  •  2.4 The location of loading in memory is also different.
    
  •  attribute:Load into heap space(wrong static)
    
  •  local variable:Load into stack space
    

*/
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("Russian");
}

}
class User{
//Attribute (or member variable)
String name; // Without private, it is the default
public int age; // It is the default without public
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 = "Stone cake";	//Stone cake: local variable
	System.out.println("Northerners like to eat:" + food);
}

}

Exercise 1

Write teacher classes and student classes, and create objects through test classes for testing
Student class
Properties:
name:String age:int major:String interests:String
Method: say() returns the student's personal information
Teacher class
Properties:
name:String age:int teachAge:int course:String
Methods: say() output the teacher's personal information

EG:

public class School {
public static void main(String[] args) {
Student stu = new Student();
stu.name = "Xiao Ming";
stu.age = 16;

	Teacher tea = new Teacher();
	tea.name = "Miss Wang";
    tea.age = 27;
    
    tea.say(stu.name,stu.age);
    stu.say(tea.name, tea.age);
}	

}
class Student{
String name;
int age;
String major;
String interests;

void say(String name, int age){
	System.out.println("This student is:"+name+"Age:"+age);	}

}
class Teacher{
String name;
int age;
String teachAge;
String course;

void say(String name, int age){
	System.out.println("The teacher is:"+name+"Age:"+age);
}

}

4.4 category 2: Methods
/*

  • Declaration and use of methods in classes
  • 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){}
    1. Method declaration: permission modifier return value type method name (formal parameter list){
  •  			Method body
    
  •  	  }
    
  • Note: static, final and abstract are used to modify the method, which will be discussed later.
    1. explain:
  •  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: there is a 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 parameter list :Method names 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 problems are analyzed in detail
    
  •  3.5 Method body:The embodiment of method function.
    
    1. Use of return keyword:
  •  1.Scope of use:Used in method body
    
  •  2.task:① End method
    
  •  	  ② For methods with return value types, use"return data"Method returns the desired data.
    
  •  3.Attention:return The executable statement cannot be declared after the keyword.
    
    1. Properties in the current class or method can be used.
  •  	special:method A Method called again in A:Recursive method.
    
  •  No other method can be defined in the method.
    

*/
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(){
//
// }

}

}

Exercise 1

Create a Person class, which is defined as follows:

public class Person {
String name;
int age;
/*
*sex:1 denotes male
*sex:0 means female
*/
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;
}

}

  • Test class
  • /*
  • requirement:
  • (1) Create an object of the Person class and set the name, age and sex properties of the object,
  • Call the study method and 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 + "Your age is" + newAge);
	
	System.out.println(p1.age);	//20
	
	//*******************************
	Person p2 = new Person();
	p2.showAge();	//0
	p2.addAge(10);
	p2.showAge();	//10
	
	p1.showAge();	//20
}

}
Exercise 2

/*

  • 2. Using the object-oriented programming method, design the class Circle to calculate the area of the Circle.
    */
    //Test class
    public class CircleTest {
    public static void main(String[] args) {
    Circle c1 = new Circle();

     c1.radius = 2.1;
     
     //Corresponding method 1:
    

// double area = c1.findArea();
// System.out.println(area);

	//Corresponding method 2:
	c1.findArea();
	//bad call
	double area = c1.findArea(3.4);
	System.out.println(area);
}

}
//Circle: 3.14rr
class Circle{
//Attributes
double radius;

//Area method of circle
//Method 1:

// public double findArea(){
// double area = 3.14 * radius * radius;
// return area;
// }
//Method 2:
public void findArea(){
double area = Math.PI * radius * radius;
System.out.println("area:" + area);
}
//Error condition:
public double findArea(Double r){
double area = 3.14 * r * r;
return area;
}
}

Exercise 3

/*

  • 3.1 write a program, declare a method method, print a 108 rectangle in the method, and call the method in the main method.
  • 3.2 modify the previous program. In the method method method, in addition to printing a 108 shaped rectangle, calculate the area of the rectangle,
  • And use it as the return value of the method. Call this method in the main method to receive the returned area value and print it.
  • 3.3 modify the previous program, provide m and n parameters in the method method, and print a mn shaped rectangle in the method,
  • And calculate the area of the rectangle as the return value of the method. Call this method in the main method to receive the returned area value and print it.

*/
public class ExerTest {

public static void main(String[] args) {
	
	ExerTest esr = new ExerTest();
	//3.1 testing

// esr.method();

	//3.2 testing
	//Mode 1:

// int area = esr.method();
// System.out.println("area:" + area);

	//Mode 2:

// System.out.println("area is:" + esr.method());

	//3.3 testing
	System.out.println("Area:" + esr.method(6,5));
}
//3.1

// public void method(){
// for(int i = 0;i < 10;i++){
// for(int j = 0;j < 8;j++){
// System.out.print("* ");
// }
// System.out.println();
// }
// }

//3.2

// public int method(){
// for(int i = 0;i < 10;i++){
// for(int j = 0;j < 8;j++){
// System.out.print("* ");
// }
// System.out.println();
// }
// return 10 * 8;
// }

//3.3
public int method(int m,int n){
	for(int i = 0;i < m;i++){
		for(int j = 0;j < n;j++){
			System.out.print("* ");
		}
		System.out.println();
	}
	return m * n;
}

}

Exercise 4

/*

    1. Object array Title: define class Student, which contains three properties:
  • Student number(int), grade state(int), 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
  • Tip: 1) generate random number: math Random(), return value type double;
  •  2) Rounding: Math.round(double d),return type long. 
    

*/
public class StudentTest {
public static void main(String[] args) {
//Declare an array of Student type
Student[] stu = new Student[20];

	for(int i = 0;i <stu.length;i++){
		//Assign values to array elements
		stu[i] = new Student();
		//Assign a value to the property of the Student's object
		stu[i].number = i + 1;
		//Grade: [1,6]
		stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
		//Score: [0100]
		stu[i].score = (int)(Math.random() * (100 - 0 + 1));
	}
	
	//Traverse student array
	for(int i = 0;i < stu.length;i++){

// System.out.println(stu[i].number + "," + stu[i].state
// + "," + stu[i].score);

		System.out.println(stu[i].info());
	}
	System.out.println("*********The following is question 1*********");
	
	//Question 1: print out the student information of grade 3 (state value is 3).
	for(int i = 0;i < stu.length;i++){
		if(stu[i].state == 3){
			System.out.println(stu[i].info());
		}
	}
	System.out.println("********The following is question 2**********");
	
	//Question 2: use bubble sorting to sort students' grades and traverse all student information.
	for(int i = 0;i < stu.length - 1;i++){
		for(int j = 0;j <stu.length - 1 - i;j++){
			if(stu[j].score >stu[j+1].score){
				//If you need to change the order, the exchange is the element of the array, Student object!!!
				Student temp = stu[j];
				stu[j] = stu[j+1];
				stu[j+1] = temp;
			}
		}
	}
	
	//Traverse student array
	for(int i = 0;i < stu.length;i++){
		System.out.println(stu[i].info());
	}
	
}

}
class Student{
int number; // Student number
int state; // grade
int score; // achievement

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

}

Exercise 4 optimization

/*

    1. Object array Title: define class Student, which contains three properties:
  • Student number(int), grade state(int), 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

  • Tip: 1) generate random number: math Random(), return value type double;

  •  2) Rounding: Math.round(double d),return type long. 
    
  • This code is for studenttest The improvement of Java encapsulates the function of operating array into method.
    */
    public class StudentTest2 {
    public static void main(String[] args) {
    //Declare an array of Student type
    Student2[] stu = new Student2[20];

     for(int i = 0;i <stu.length;i++){
     	//Assign values to array elements
     	stu[i] = new Student2();
     	//Assign a value to the property of the Student's object
     	stu[i].number = i + 1;
     	//Grade: [1,6]
     	stu[i].state = (int)(Math.random() * (6 - 1 + 1) + 1);
     	//Score: [0100]
     	stu[i].score = (int)(Math.random() * (100 - 0 + 1));
     }
     
     StudentTest2 test = new StudentTest2();
     
     //Traverse student array
     test.print(stu);
     
     System.out.println("*********The following is question 1*********");
     
     //Question 1: print out the student information of grade 3 (state value is 3).
     test.searchState(stu, 3);
     System.out.println("********The following is question 2**********");
     
     //Question 2: use bubble sorting to sort students' grades and traverse all student information.
     test.sort(stu);
     
     //Traverse student array
     for(int i = 0;i < stu.length;i++){
     	System.out.println(stu[i].info());
     }
    

    }

    /**
    *

    • @Description operation of traversing Student [] array
    • @author subei
    • @Date April 15, 2020 8:25:36 PM
    • @param stu
      */
      public void print(Student2[] stu){
      for(int i = 0;i < stu.length;i++){
      System.out.println(stu[i].info());
      }
      }

    /**
    *

    • @Description find the learning information of the specified grade in the Student array
    • @author subei
    • @Date: April 15, 2020 8:22:34 PM
    • @param stu
    • @param state
      */
      public void searchState(Student2[] stu,int state){
      for(int i = 0;i < stu.length;i++){
      if(stu[i].state == state){
      System.out.println(stu[i].info());
      }
      }
      }

    /**
    *

    • @Description sorts the Student array
    • @author subei
    • @Date: April 15, 2020 8:24:33 PM
    • @param stu
      */
      public void sort(Student2[] stu){
      for(int i = 0;i < stu.length - 1;i++){
      for(int j = 0;j <stu.length - 1 - i;j++){
      if(stu[j].score >stu[j+1].score){
      //If you need to change the order, the exchange is the element of the array, Student object!!!
      Student2 temp = stu[j];
      stu[j] = stu[j+1];
      stu[j+1] = temp;
      }
      }
      }
      }
      }
      class Student2{
      int number; // Student number
      int state; // grade
      int score; // achievement

    //Method of displaying student information
    public String info(){
    return "student number:" + number + ", grade:" + state + ", grade:" + score ";
    }
    }

Tags: Java

Posted by jtmathome on Thu, 19 May 2022 17:36:01 +0300