Introduction to the latest Java foundation in 2021

Posted by Theophilus on Tue, 08 Mar 2022 12:04:04 +0100

Introduction to the latest Java foundation in 2021 (3)

The third chapter is coming. This time it mainly introduces classes and objects, encapsulation and construction methods

preface

If you don't say much, go straight to the dry goods

1, Object oriented thought

1.1 overview of object-oriented thought

Java language is an object-oriented programming language, and object-oriented idea is a programming idea. Under the guidance of object-oriented idea, we use java language to design and develop computer programs. The object here generally refers to all things in reality, and each thing has its own attributes and behavior. The object-oriented idea is the design idea of abstracting the attribute characteristics and behavior characteristics of things with reference to real things in the process of computer programming and describing them as computer events. Different from the process oriented idea, it emphasizes that the function is realized by calling the behavior of the object, rather than operating and realizing it step by step.

characteristic
Object oriented thinking is an idea that is more in line with our thinking habits. It can simplify complex things and turn us from executor to commander. Object oriented language contains three basic features, namely encapsulation, inheritance and polymorphism.

1.2 classes and objects

Looking around, you will find many objects, such as tables, chairs, classmates, teachers and so on. Desks and chairs belong to office supplies, and teachers and students are human beings. So what is a class? What is an object?

What is a class

A class is a collection of related properties and behaviors. It can be regarded as the template of a kind of things, and the attribute characteristics and behavior characteristics of things are used to describe this kind of things.

In reality, describe a class of things:

  • Attribute: is the state information of the thing.
  • Behavior: is what the thing can do.

Example: kitten.
Attributes: name, weight, age, color.
Behavior: walking, running and shouting

What is an object

Object is the concrete embodiment of a kind of things. An object is an instance of a class (an object is not looking for a girlfriend), which must have the properties and behavior of such things.

In reality, an example of a kind of thing: a kitten.
Example: a kitten.
Attributes: tom, 5kg, 2 years, yellow.
Behavior: sneaking around the wall, jumping and running, meowing.

Relationship between class and object

  • Class is the description of a class of things, which is abstract.
  • An object is an instance of a class of things and is concrete.
  • Class is the template of object, and object is the entity of class

1.3 definition of class

Comparison of things and classes

A class of things in the real world:

  • Attribute: state information of things.
  • Behavior: what can things do

The same is true of using class to describe things in Java:

  • Member variable: the attribute of the corresponding thing
  • Member method: the behavior of corresponding things

Class definition format

public class Student {
	//Member variable
	String name;//full name
	int age;//Age

	//Member method
	//Learning methods
	publicvoid study() {
		System.out.println("study hard and make progress every day");
	}
	//How to eat
	publicvoid eat() {
		System.out.println("Learn to eat when you are hungry");
	}
}

Define class: defines the members of a class, including member variables and member methods.
Member variables: almost the same as previously defined variables. It's just that the location has changed. In a class, outside a method.
Member method: it is almost the same as the previously defined method. Just remove static. The function of static will be explained in detail later in the course of object-oriented

1.4 use of objects

Use format of object

Class name object name = new Class name();

Using objects to access members in a class

Object name.Member variables;
Object name.Member method();

Example of object format

public class Test01_Student {
	public static void main(String[] args) {
		//Create object format: class name object name = new class name ();
		Student s = new Student();
		System.out.println("s:"+s); //cn.itcast.Student@100363
		//Direct output of member variable values
		System.out.println("full name:"+s.name); //null
		System.out.println("Age:"+s.age); //0
		System.out.println("‐‐‐‐‐‐‐‐‐‐");
		//Assign values to member variables
		s.name = "Zhao Liying";
		s.age = 18;
		//Output the value of the member variable again
		System.out.println("full name:"+s.name); //Zhao Liying
		System.out.println("Age:"+s.age); //18
		System.out.println("‐‐‐‐‐‐‐‐‐‐");
		//Call member method
		s.study(); // "Study hard and make progress every day"
		s.eat(); // "Learn to eat when you're hungry"
	}
}

Default value of member variable

1.5 class and object exercises

Define mobile phone class:

public class Phone {
	// Member variable
	String brand; //brand
	int price; //Price
	String color; //colour
	// Member method
	//phone
	public void call(String name) {
		System.out.println("to"+name+"phone");
	}
	//send message
	public void sendMessage() {
		System.out.println("Mass texting");
	}
}

Define test class:

public class Test02Phone {
	public static void main(String[] args) {
		//create object
		Phone p = new Phone();
		//Output member variable value
		System.out.println("Brand:"+p.brand);//null
		System.out.println("Price:"+p.price);//0
		System.out.println("Color:"+p.color);//null
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");
		//Assign values to member variables
		p.brand = "hammer";
		p.price = 2999;
		p.color = "brown";
		//Output the member variable value again
		System.out.println("Brand:"+p.brand);//hammer
		System.out.println("Price:"+p.price);//2999
		System.out.println("Color:"+p.color);//brown
		System.out.println("‐‐‐‐‐‐‐‐‐‐‐‐");
		//Call member method
		p.call("Zixia");
		p.sendMessage();
	}
}

1.6 object memory diagram

Memory map of an object using the same method

Memory map of two objects using the same method

Two references point to the memory map of the same object

1.7 differences between member variables and local variables

We define variables according to their different positions. As shown in the figure below:

  • Different positions in the class focus
    • Member variable: in class, outside method
    • Local variable: in method or on method declaration (formal parameter)
  • The scope of action is different and the focus is different
    • Member variables: in classes
    • Local variables: in method
  • Different focus of initialization value
    • Member variables: have default values
    • Local variable: no default value. Must first define, assign, and finally use
  • Different locations in memory
    • Member variables: heap memory
    • Local variables: stack memory
  • Different understanding of life cycle
    • Member variable: exists with the creation of the object and disappears with the disappearance of the object
    • Local variable: exists with the method call and disappears with the method call

2, Encapsulation

2.1 package overview

Object oriented programming language is a simulation of the objective world. In the objective world, member variables are hidden in the object, and the outside world cannot operate and modify them directly. Encapsulation can be considered as a protective barrier to prevent the code and data of this class from being freely accessed by other classes. To access the data of this class, you must use the specified method. Proper encapsulation can make the code easier to understand and maintain, and also strengthen the security of the code.

principle

Hide the property. If you need to access a property, provide public methods to access it

2.2 steps of packaging

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

2.3 encapsulated operation - private keyword

Meaning of private

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

Use format of private

private Data type variable name;
  1. Use private to modify member variables. The code is as follows
public class Student {
   private String name;
   private int age;
}
  1. Provide getXxx method / setXxx method to access member variables. The code is as follows:
public class Student {
   private String name;
   private int age;
   public void setName(String n) {
   	name = n;
   }
   public String getName() {
   	return name;
   }
   public void setAge(int a) {
   	age = a;
   }
   public int getAge() {
   	return age;
   }
}

2.4 package optimization 1 - this keyword

We found that the formal parameter name in setXxx method does not meet the requirement of knowing the meaning by name. If the modification is consistent with the member variable name, is it known by name? The code is as follows:

public class Student {
	private String name;
	private int age;
	public void setName(String name) {
		name = name;
	}
	public void setAge(int age) {
		age = age;
	}
}

After modification and testing, we found a new problem. The assignment of member variables failed. In other words, after modifying the formal parameter variable name of setXxx(), the method does not assign a value to the member variable! This is because the formal parameter variable name is the same as the member variable name, resulting in the member variable name being hidden, and the variable name in the method cannot access the member variable, so the assignment fails. We can only use this keyword to solve this problem.

The meaning of this
this represents the reference (address value) of the current object of the class, that is, the reference of the object itself.

tips:
	Method is called by which object, and the this It represents that object. That is, who is calling, this On behalf of whom.

this use format
this. Member variable name;
Use the variable in this modification method to solve the problem that the member variable is hidden. The code is as follows:

public class Student {
	private String name;
	private int age;
	public void setName(String name) {
		//name = name;
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setAge(int age) {
		//age = age;
		this.age = age;
	}
	public int getAge() {
		return age;
	}
}
tips:
	When there is only one variable name in the method, it is also used by default this You can omit the modification, you can't write it.

2.5 package optimization 2 - construction method

When an object is created, the constructor is used to initialize the object and assign the initial value to the member variable of the object.

tips:
Whether you customize the construction method or not, all classes have construction methods, because Java automatically provides a parameterless construction method. Once you define the construction method, the default parameterless construction method automatically provided by Java will become invalid.

Definition format of construction method
The method name is the same as the class name of the constructor. It doesn't have a return value, so it doesn't need a return value type, or even void. After using the construction method, the code is as follows:

public class Student {
	private String name;
	private int age;
	// Nonparametric construction method
	public Student() {}
	// Parametric construction method
	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}
}

matters needing attention

  1. If you do not provide a construction method, the system will give a parameterless construction method.
  2. If you provide a construction method, the system will no longer provide a parameterless construction method.
  3. The construction method can be overloaded, and parameters can be defined or not.

2.6 Standard Code - JavaBean

JavaBean is a standard specification of classes written in Java language. Classes that conform to JavaBean are required to be concrete and public, and have parameterless construction methods, providing set and get methods for operating member variables.
Write classes that conform to JavaBean specifications. Take student classes as an example. The standard code is as follows:

public class Student {
	//Member variable
	private String name;
	private int age;
	//Construction method
	public Student() {}
	public Student(String name,int age) {
		this.name = name;
		this.age = age;
	}
	//Member method
	publicvoid setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	publicvoid setAge(int age) {
		this.age = age;
	}
	publicint getAge() {
		return age;
	}
}

The test class code is as follows:

public class TestStudent {
	public static void main(String[] args) {
		//Use of parameterless construction
		Student s= new Student();
		s.setName("Liuyan");
		s.setAge(18);
		System.out.println(s.getName()+"‐‐‐"+s.getAge());
		//Use of structure with parameters
		Student s2= new Student("Zhao Liying",18);
		System.out.println(s2.getName()+"‐‐‐"+s2.getAge());
	}
}

summary

Continuous update!!!

Topics: Java Back-end