Object-Oriented Programming (Basics) 10: The third member of a class: Constructor

When we finish the new object, all member variables have default values. If we need to assign new values, we need to assign values ​​to them one by one, which is too troublesome. Can we directly assign values ​​to some or all member variables of the current object when new objects are created?

Yes, Java provides us with 构造器(Constructor), also known as 构造方法.

10.1 The role of the constructor

new object, and assign values ​​​​to instance variables when new objects are created.

Example: Person p = new  Person(“Peter”,15);

Explanation: Just as we stipulate that each "person" must take a bath as soon as he is born, we can add the program code to complete the "bath" in the constructor of the "person", so that each "person" will automatically complete the "bath" as soon as he is born. Take a bath" instead of telling each individual to "take a bath" one by one when they are newborns.

10.2 Syntax of constructors

[修饰符] class 类名{
    [修饰符] 构造器名(){
    	// 实例初始化代码
    }
    [修饰符] 构造器名(参数列表){
        // 实例初始化代码
    }
}

illustrate:

  1. The constructor name must be the same as the class name in which it resides.
  2. It has no return value, so no return type is needed, nor void.
  3. The modifier of the constructor can only be a permission modifier and cannot be modified by any other. For example, it cannot be modified by static, final, synchronized, abstract, native, and cannot have a return statement return value.

code show as below:

public class Student {
    private String name;
    private int age;

    // 无参构造
    public Student() {}

    // 有参构造
    public Student(String n,int a) {
        name = n;
        age = a;
    }

    public String getName() {
        return name;
    }
    public void setName(String n) {
        name = n;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int a) {
        age = a;
    }

    public String getInfo(){
        return "姓名:" + name +",年龄:" + age;
    }
}

public class TestStudent {
    public static void main(String[] args) {
        //调用无参构造创建学生对象
        Student s1 = new Student();

        //调用有参构造创建学生对象
        Student s2 = new Student("张三",23);

        System.out.println(s1.getInfo());
        System.out.println(s2.getInfo());
    }
}

10.3 Instructions for use

  1. When we do not explicitly declare the constructor in the class, the system will provide a parameterless constructor by default and the modifier of the constructor is the same as the modifier of the class by default.

  2. When we explicitly define the class constructor, the system no longer provides a default no-argument constructor.

  3. In a class, there will be at least one constructor.

  4. Constructors can be overloaded.

10.4 Exercises

**Exercise 1:

**Write two classes, TriAngle and TriAngleTest, where the private base length base and height are declared in the TriAngle class, and public methods are declared to access private variables. Additionally, provide the necessary constructors for the class. Use these public methods in another class to calculate the area of ​​the triangle.

Exercise 2:

(1) Define the Student class, which has 4 attributes:
String name;
int age;
String school;
String major;

(2) Define three constructors of the Student class:

  • The first constructor Student(String n, int a) sets the name and age properties of the class;
  • The second constructor Student(String n, int a, String s) sets the name, age and school properties of the class;
  • The third constructor Student(String n, int a, String s, String m) sets the name, age, school and major properties of the class;

(3) Call the objects created by different constructors in the main method, and output their property values.

Exercise 3:

1. Write a class demo account named Account. The properties and methods of this class are shown in the figure below.

The attributes included in this class: account id, balance balance, annual interest rate annualInterestRate;

Included methods: accessor methods (getter and setter methods), withdrawal method withdraw(), deposit method deposit().

**Reminder:** In the withdrawal method withdraw, it is necessary to judge whether the user balance can meet the requirements of the withdrawal amount, and if not, a reminder should be given.

  1. Create a Customer class.

a. Declare three private object properties: firstName, lastName, and account.
b. Declare a public constructor with two parameters representing object properties (f and l)
c. Declare two public accessors to access the object properties. The methods getFirstName and getLastName return the corresponding properties.
d. Declare the setAccount method to assign a value to the account property.
e. Declare the getAccount method to get the account property.

3. Write a test program.

(1) Create a Customer named Jane Smith, who has an account number of 1000, a balance of 2000 yuan, and an account with an annual interest rate of 1.23%.
(2) Action on Jane Smith.
Deposit 100 yuan and withdraw 960 yuan. Take out another 2,000 yuan.
Print out the basic information of Jane Smith

成功存入 :100.0
成功取出:960.0
余额不足,取款失败
Customer [Smith, Jane] has a account: id is 1000, annualInterestRate is 1.23%, balance is 1140.0

Guess you like

Origin blog.csdn.net/swx595182208/article/details/129975478