The nature of classes and objects

Posted by FURQAN on Tue, 04 Jan 2022 21:22:21 +0100

The nature of classes and objects

Nature of class

8 Basic data types,When we need what type,That is, customize it

class Custom data type User

The process is described in combination with attributes and methods,Operation cannot be called in class

use: int i = 10; use i You must declare(Include data types)And initialization,Further use of variables in programs i Participate in operation

User user(Variables generated by class types,object) = new User();

User Is type,user Is an object,Assigned,user Object is instantiated,therefore,object user yes User An example of ,

Assignment process: new User(); 

If not new assignment, Then the object will have a default value: null

Class type(class Declarative)Also called object type

There are three types of objects:

- class Declared custom class
- String type(Essentially still class type)
- array int\[\] arr = new int\[length\]; Because object types can define properties and methods(In order to get length)

The nature of objects

The nature of objects,Is an instance of a class(instance/ initialize instantiation  )

Instantiation process: adopt new className() Allocate memory, Then pass the first memory address to the object ,therefore,Object is the first address that references a piece of memory

therefore, Object types can also be called references(reference)type

Reference: quote, Remote control equivalent to TV

If the object is not initialized(Unreferenced address,At this time, the object saves the default value null), and null You cannot perform operations,Throw an exception if executed: NullPointerException

Why not new User() Directly as the object of the operation?

new User() Although you can't do secondary operation, But if you do it only once? tolerable

Relationship between classes and objects

Classes are public templates, and objects are concrete individuals

Classes are public types and objects are instances

Class is responsible for description and object is responsible for execution

Legend of classes and objects in memory

Heap memory and stack memory: heap is slow and not suitable for repeated operation. Stack is suitable for fast reading and writing and repeated operation

The object is directly assigned a value through the object and the object is null

public static void main(String[] args) {
		// Generate objects with User
		User user1 = new User();
		user1.name = "Ren Xinyue";
		
		
		User user2 = user1;
		user2.name = "Jiang Zhiwei";
		
		System.out.println("user1:"+user1);
		System.out.println("user2:"+user2);
		
		System.out.println("user2.name:"+user2.name);   //Jiang Zhiwei
		System.out.println("user1.name:"+user1.name);  	//Jiang Zhiwei
		
		// new User() is also a garbage memory
		// Application scenario: it is applicable when only one operation needs to be called (form swing)
		System.out.println(new User());
		new User().name = "Xue You Zhang";
		System.out.println(new User().name);  //Default value for null string
		
		
		// null is the default value for all object types
		User user3 = null ;
		System.out.println("user3:"+user3);
		 // java specifies that null objects cannot perform calling operations, otherwise null pointerexception will be thrown
		user3.name = "Zhang Manyu"; 
		
	}

new keyword

  • Call constructor

  • Open up memory

  • Passing references: passing references to objects

Construction method

User()

concept

The method name is exactly the same as the class name (including case). A method without return value is defined in the class

use

It can only be called through new when the object is instantiated

characteristic:

  1. Each class has a default constructor in the form of:

ClassName(){}

  1. The default construction method (implicit construction method) can be overridden. The construction method that overrides it is called explicit construction method

    public class User {
    	
    	// User number
    		String id ;
    		
    		// User name
    		String name;
    		
    		// User mobile phone
    		String phone;
    		
    		// User password
    		String pwd;
    		
    		//User age
    		int age;
    	
    	//int i ;
    	// Actively create a construction method:
    	/*
    	 * User(){ System.out.println("This is a User constructor ');}
    	 */
    
    	// Assign initial values to the member fields in the class through the parameters of the construction method
    	User(String name,String phone,int age){		
    		// Assign a value to i in the construction method
    		//i = 10;
    		
    		this.name = name;
    		this.age = age;
    		this.phone = phone;
    		
    	}
    	
    	// If you want to use the construction method of null parameters, use overloading
    	// Overload: there are multiple methods in the class with the same method name and different parameters,
    	//Overload is formed between them, which is represented by overload
    	User(){
    		// Constructors can call each other: this()
    		// Call the constructor with phone parameter:
    		this("13312345678");
    	}
    	
    	User(String phone){
    		this.phone = phone;
    	}
    }
    

Overloading of construction methods

Overload concept

There are multiple methods in the class. If their method names are the same and their parameters are different, an overload is formed between them, which is represented by overload

Next, we use the concept of overloading to process the construction method:

// Assign initial values to the member fields in the class through the parameters of the construction method
	User(String name,String phone,int age){		
		// Assign a value to i in the construction method
		//i = 10;
		
		this.name = name;
		this.age = age;
		this.phone = phone;
		
	}
	
	// If you want to use the construction method of null parameters, use overloading
	// Overload: there are multiple methods in the class with the same method name and different parameters,
	//Overload is formed between them, which is represented by overload
	User(){
		// Constructors can call each other: this()
		// Call the constructor with phone parameter:
		this("13312345678");
	}
	
	User(String phone){
		this.phone = phone;
	}

effect:

  1. Enable objects to be instantiated (the main function in practice)

  2. Define the operations that the object needs to perform from the beginning in the construction method

  3. Assign initial values to attributes through parameters (not necessary)

Global and local scopes in class:

The variable name defined in the parameter / internal of the method is a local scope (which can only be accessed within the method)

If global and local variables have the same name, local variables have higher priority (proximity principle)

this is used in java to distinguish variables with the same name in attributes and methods

		// User name
		String name;
		
		// User mobile phone
		String phone;
		
		//User age
		int age;
// Assign initial values to the member fields in the class through the parameters of the construction method
	User(String name,String phone,int age){
		
		this.name = name;
		this.age = age;
		this.phone = phone;
		
	}

this keyword

Keyword, which is equivalent to an object, can only be used in the internal methods of a class and can represent an object

effect

It is used to distinguish between global and local contents with the same name. When the contents called through this are defined in the class

// Assign initial values to the member fields in the class through the parameters of the construction method
	User(String name,String phone,int age){
		
		// Assign a value to i in the construction method
		//i = 10;
		
		this.name = name;
		this.age = age;
		this.phone = phone;
		
	}

Design of Plants vs. Zombies

public class Zombie {
	// Fields (properties)
	// aggressivity
	int attack;

	// Defensive power
	int defense;

	// Life value
	int hp;

	// name
	String name;

	// method
	// Construction method

	Zombie(String name, int attack, int defence, int hp) {
		this.name = name;
		this.attack = attack;
		this.defense = defence;
		this.hp = hp;
	}
	
	/**
	 *Add another parameter free construction method 
	 *Make objects more flexible when creating
	 */
	Zombie() {
		
	}
	

	/**
	 * When zombies encounter plants, melee methods
	 * Business: zombie attack, plant defense,
	 * Number of attacks continued until HP = 0
	 */
	void fight(Plant plant) {
		// In the current class, you can use this to represent your own object
		System.out.println(this.name+"Attack"+plant.name);
		while (plant.hp>0) {
			plant.hp -= this.attack-plant.defense;
			System.out.println(plant.name+"Remaining"+plant.hp+"blood");
			
			// Through thread The sleep method stops the program
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("The battle is over,"+plant.name+"cover"+this.name+"Kill it");
	}

}

Three reference types in java

The 8 basic data types are common data types
Custom classes and existing types in the jdk can become object types to create objects
An object is essentially a reference to the first address of memory, and an object type is called a reference type

  1. Class (initial capital)

  2. array

  3. String

public static void main(String[] args) {
		// Declare an array of int s
		int[] arr = new int[10];
		
		System.out.println(arr[0]);
		System.out.println(Arrays.toString(arr));
		
		//[I@2401f4c3
		System.out.println(arr);
	}

The characteristic of object type assignment is that the object type passes the reference of memory address. Therefore, when assigning values between object types, this reference relationship will continue to pass, which is essentially the same object

public static void main(String[] args) {
		//First, judge whether there is 1 in the stack memory. If so, point the memory to a
		//If not, open up
		//b when assigning values, judge
		int a = 1; //Literal 
		int b = a;  //
		System.out.println("b:"+b);
		b=2;
		System.out.println("b:"+b);
		System.out.println("a:"+a);
		
		
		//Change to type: Plant
		Plant p1 = new Plant();
		p1.name="Tall-nut ";
		
		Plant p2 = p1;
		System.out.println(p2.name);
		p2.name = "Wogua";
		System.out.println(p2.name);
		System.out.println(p1.name);
	}

Although the String type is also an object type, java optimizes it

Refer to the following codes for specific comparison:

//String pass reference
		/*
		 * String str1 = "abc"; String str2 = str1; str2 = "abcd";
		 * System.out.println("str1:"+str1);
		 */
		
		/*
		 * String str1 = "abc"; String str2 = "abc";
		 * System.out.println(str1.equals(str2)); //true
		 */		
		
		/*
		 * String str1 = "abc"; String str2 = "abcd";
		 * System.out.println(str1.equals(str2)); //false
		 */		
		
		// When the string uses new String(), it is no longer referenced in the constant pool, but in the heap
		String str1 = new String("abc");
		String str2 = new String("abc");
		
		// ==The object type uses concatenation, which compares whether the first memory address is the same
		System.out.println(str1 == str2);   //false , 
		//equals is the way to compare content
		System.out.println(str1.equals(str2));  //true
		
		String str11 = "abc";
		String str22 = "abc";
		System.out.println(str11 == str22);  // true
		System.out.println(str11.equals(str22));  // true
		
		String str111 = "abc";
		String str222 = new String("abc");
		System.out.println(str111 == str222);  // false
		System.out.println(str111.equals(str222));  // true
		
		// Optimization of java in String constants
		String str1111 = "abc";
		String str2222 = "ab"+"c";
		System.out.println(str1111 == str2222);  // true
		System.out.println(str1111.equals(str2222));  // true

Performance of String in memory

java stores the value of the string in the constant pool in order to speed up the access speed of the string

How many String objects will be generated in the following code?

	//How many string objects were created?
	// The answer is 2: "ABC" generates one string in the constant pool
	String string = new String("abc");
	

	// The answer is 3: "ABC" generates one in the constant pool, one in str1 and one in str2, a total of 3
	String str1 =new String ("abc");
	String str2 =new String ("abc");

Role of final

  1. When a variable is declared, it represents a constant

  2. Declare classes that cannot be inherited (learn from the chapter on inheritance)

  3. Declared methods cannot be overridden (learn in the polymorphic section)

public class Demo3 {
	// final modifies a variable and becomes a constant. The constant must be given an initial value and cannot be changed later
	// Constants are generally recommended to be named in all uppercase
	//final int i = 1;
	//final int I = 1;
	 final double PI = 3.14;
	public static void main(String[] args) {
		Demo3 demo3 = new Demo3();
	//	demo3.i = 2;

	}

}