Java basic self-study notes-Chapter 9: Objects and classes

Chapter 9: Objects and Classes

1. Define the class for the object

  • A class defines properties and behaviors for objects. A class is a template, blueprint or contract
  • An object is an instance of a class. A class can create multiple instances. The process of creating an instance is also called instantiation
  • The constructor is used to complete initialization actions, such as initializing the data field of the object
  • Java uses variables to define data fields and methods to define actions
  • Unified Modeling Language (UML) is also known as class diagram

Two. Define the class and create the object

The class is the definition of the object, and the object is created from the class

No-argument construction has priority over private member variables

public class TestCircle{
    
    
    public static void main(String[] args){
    
    
    Circle circle=new Circle();
    //可以通过两种方式修改circle的半径
    //circle.radius=4;
    //circle.setRadius(4);
    System.out.println(circle.radius);//2.0
    }
}
class Circle{
    
    
    double radius=1.0;
	Circle(){
    
    
		radius=2.0;
	}
	void setRadius(double r) {
    
    
		radius=r;
	}
}

You can put two classes in a folder, but there can only be one public class, and the public class must have the same name as the file name, and two class files will be generated during compilation.

Note that
if no parameter structure and member variables are not assigned initial values, the default is 0

Create an object reference variable circle, create an object, and assign a reference to this object to this variable

   Circle circle=new Circle();
// 类型  对象引用  创建一个对象

Three. Use the constructor to create an object

The constructor is called when the object is created using the new operator

The particularity of the construction method:

  • Must be the same as the class name
  • No return value type
  • The role is to initialize the object

There can be multiple construction methods with different signatures to facilitate the construction of objects with different initial values

There is no need to define a construction method in a class. By default, a no-parameter construction with an empty method body is implied. It will be automatically provided if and only if the construction method is not clearly defined
Insert picture description here
in the class. The reason is that the class already has a construction method. The default no-argument construct will no longer be called

Four. Access objects through reference variables

1. The data and methods of the object are accessed through the dot operator

2. The above data domain radius is an instance variable, because it depends on a specific instance

3. The reason why the Math.pow() method is called directly without creating an instance is because the methods in the Math class are static

4. Sometimes an object does not need to be referenced after it is created, which is called an anonymous object.
Insert picture description here
5. The data field of the reference type is null by default, such as String type, etc.

6. The assignment of the object type is to assign a reference to a variable, and two references after the assignment point to an object

7. NullPointerException (NullPointerException)
If the object reference is not assigned to this variable, call the data field and method of the object, which will cause a null pointer exception
Insert picture description here

5. Use classes in the Java library

1.Date class

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Date date = new Date();// 为当前时间创建一个date对象
		Date date2 = new Date(3215245);// 从1970年1月1日以毫秒为单位计算给定时间的date对象
		System.out.println(date.toString());// 返回日期和时间的字符串表示
		//结果:Sat Feb 15 22:19:49 CST 2020
		System.out.println(date2.toString());// 返回日期和时间的字符串表示
		//结果:Thu Jan 01 08:53:35 CST 1970
		System.out.println(date.getTime());// 返回从1970年1月1日至今的毫秒数
		//结果:1581776389841
		date.setTime(1234564);// 设置一个新的流逝时间
		System.out.println(date.toString());
		//结果:Thu Jan 01 08:20:34 CST 1970
	}

2.Random class

		Random random = new Random();// 当前时间作为种子创建Random对象
		Random random2 = new Random(456432154);// 以一个特定值作为种子创建一个Random对象
		System.out.println(random.nextInt());// 返回随机一个整数
		System.out.println(random.nextInt(6));// 返回6以内的不包含6的随机整数
		System.out.println(random.nextLong());// 随机long值
		System.out.println(random.nextDouble());// 随机[0.0-1.0)
		System.out.println(random.nextFloat());// 随机[0.0F-1.0F)
		System.out.println(random.nextBoolean());// 随机boolean值

note

When creating a Random object, you must specify a seed or default seed. If the seeds are the same, they will produce the same sequence, which is very important in software testing

6. Static variables, constants and methods

Static variables are shared by all objects in the class, static methods cannot access instance members in the class

Static variables are stored in a public memory address

Static members and static methods are best called using class names to improve readability

System.out.println(Circle.PI);//3.14

class Circle {
    
    
	double radius = 1.0;
	static final double PI = 3.14;//定义常量,常量通常是要被对象共享的,所以用static修饰
	Circle(double r) {
    
    
		radius = r;
	}
}

note

Instance methods can access instance members and instance methods

Static methods can only access static members and static methods

Seven. Visibility modifier

Modifier Accessibility class Construction method method data Piece
(default) no modifier In-package access Yes Yes Yes Yes Yes
public Unlimited access Yes Yes Yes Yes no
private In-class access no Yes Yes Yes no
protected Accessible to classes in the package and subclasses of other packages no Yes Yes Yes no

In order to prevent the creation of an instance of the class, private modification of the class construction method such as the Math class can be used

private Math()

8. Data field encapsulation

Set the data domain as private protection data and make the class easy to protect

In order to avoid the direct modification of the data field, use private modification to set the data field as private, which is called data field encapsulation

To be able to access and set the new value, use the get() accessor and set() modifier

Friends who are proficient in writing accessors and modifiers can click on the menu bar Source->Getters and Setters in Eclipse to quickly create

class Circle {
    
    
	double radius = 1.0;
	static final double PI = 3.14;
	
	public double getRadius() {
    
    
		return radius;
	}

	public void setRadius(double radius) {
    
    
		this.radius = radius;
	}

	double getArea() {
    
    
		return radius*radius*PI;
	}
}

Nine. Passing object parameters to the method

Passing an object to the method is to pass the reference of the object to the object, and the referenced object and the passed object are the same

Note: The
following example shows a shallow copy. When circle and circle2 are passed to the swap method, a copy of them will be generated. Changing the address of the copy has no effect on the original.

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Circle circle = new Circle();
		Circle circle2 = new Circle();

		System.out.println(circle);// 交换前circle指向的地址   T_T.Circle@668bc3d5
		System.out.println(circle2);// 交换前circle2指向的地址   T_T.Circle@3cda1055

		swap(circle, circle2);// 进行交换
		System.out.println();

		System.out.println(circle);// 交换后circle指向的地址   T_T.Circle@668bc3d5
		System.out.println(circle2);// 交换后circle2指向的地址   T_T.Circle@3cda1055
	}

	public static void swap(Circle A, Circle B) {
    
    
		Circle C = A;
		A = B;
		B = C;
	}

Involving reference exchange, the original address of the new object created for the reference remains unchanged

10. Immutable objects and classes

1. You can define an immutable class to produce an immutable object, and the content of the immutable object cannot be changed

2. Conditions for immutable classes

  • No set modifier
  • Variables are static
  • There is no accessor construct that points to a reference to a variable data field, such as the setTime() method in the Data class

11. The scope of variables

1. Instance variables or static variables of a class are called class variables or data fields, and variables defined in methods are called local variables.

2. The methods and variables in the class can appear in any order, but if a data field is initialized based on another data field reference

class Circle {
    
    

	public double getRadius() {
    
    
		return radius;
	}

	public void setRadius(double radius) {
    
    
		this.radius = radius;
	}

	public Circle() {
    
    

	}

	double getArea() {
    
    
		return radius * radius * PI;
	}

	double radius = 1.0;
	static final double PI = 3.14;
}

The following example requires attention

int i=2;
int j=i+2;//j的值依赖于i,所以位置不能互换

3. If a local variable and a class variable have the same name, the local variable takes precedence, and the class variable with the same name will be hidden, so in order to avoid confusion and errors, try not to use the local variable with the same name as the class variable.

4. The static{} and {} code fields in the class

		Circle circle = new Circle();
		Circle circle2 = new Circle();

       //运行结果:
      // 静态代码域,在类加载的时候调用一次,整个生命周期就只会调用一次
      // 普通代码域,类的每个对象创建时都会调用
      // 普通代码域,类的每个对象创建时都会调用

	static {
    
    
		System.out.println("静态代码域,在类加载的时候调用一次,整个生命周期就只会调用一次");
	}

	{
    
    
		System.out.println("普通代码域,类的每个对象创建时都会调用");
	}

note

  • The variables defined in the code domain are all local and can only be used in the code domain
  • If it is an internal class, you must use a static internal class to define a static code block
  • Priority: static code block>main method>construction code block>construction method
class Student {
    
    
		static {
    
    
			System.out.println("Student 静态代码块");
		}
		
		{
    
    
			System.out.println("Student 构造代码块");
		}
		
		public Student() {
    
    
			System.out.println("Student 构造方法");
		}
}
	
class StudentTest {
    
    
    static {
    
    
        System.out.println("StudentTest静态代码块");
    }

    public static void main(String[] args) {
    
    
        System.out.println("我是main方法");

        Student s1 = new Student();
        Student s2 = new Student();
    }
}

//结果:
//StudentTest静态代码块
//我是main方法
//Student 静态代码块
//Student 构造代码块
//Student 构造方法
//Student 构造代码块
//Student 构造方法

Twelve.this quote

1. The keyword this refers to the object itself, you can call other construction methods within the construction method

class Circle {
    
    
	double radius;
	static final double PI = 3.14;

	public Circle() {
    
    
		this(1.0);//调用其他构造方法
	}

	public Circle(double radius) {
    
    
		this.radius = radius;//这个this关键字用于引用所构建的对象的隐藏数据域radius
	}
}

2. Instance members of reference objects

    Circle circle = new Circle(3);//28.6

	public Circle(double radius) {
    
    
		this.radius = radius;
		System.out.println(this.getArea());
	}

3. If you refer to the hidden data field and call an overloaded constructor, this reference is necessary

4. Hidden static variables can be realized by class name. Static variables, the hiding of instance variables needs this to call

note

  • Java requires that in the construction method, the statement this (parameter list) should be before other statements
  • If there are multiple construction methods in a class, it is best to use this (parameter list) to implement them as much as possible. Generally, a construction method with no or fewer parameters can use this (parameter list) to call a construction method with more parameters.

13. Summary

Through the study of this chapter, I know the meaning of classes and objects, and how to define them, create objects by constructing methods, access objects by referencing variables, and learn an exception (null pointer exception, more exceptions will be introduced later) , Know how to define static variables and constants, it is best to use the class to call them directly when calling them, learned the benefits of encapsulating data and passing object parameters to methods, shallow copy. Understand how to create an immutable class and variable scope, the priority of static code domain and construction code domain, and learn the super practical role of this reference.

Guess you like

Origin blog.csdn.net/weixin_42563224/article/details/104332969