Java from entry to proficiency - classes and objects (3)

1.6 Practice and Exercise

Insert image description here

1.1 Overview of object-oriented

Basic exercises:

1. Create a class Personwith two member variables: name and age, and a method displayInfo()for displaying name and age. Then create an Personobject and call displayInfo()the method.

public class Person {
    // 成员变量
    private String name;
    private int age;

    // 构造方法
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // 成员方法用于显示姓名和年龄
    public void displayInfo() {
        System.out.println("姓名: " + name);
        System.out.println("年龄: " + age);
    }

    public static void main(String[] args) {
        // 创建Person对象并初始化
        Person person1 = new Person("Alice", 25);

        // 调用displayInfo()方法来显示信息
        System.out.println("个人信息:");
        person1.displayInfo();
    }
}

Code explanation:

  1. We have created a Personclass called which has two member variables name(name) and age(age).

  2. In the constructor, we accept two parameters for initializing the member variables nameand age.

  3. There is a displayInfo()member method called in the class which is used to display the name and age.

  4. In mainthe method, we create an Personobject person1and initialize the name and age of the object through the constructor method.

  5. Finally, we call person1the object's displayInfo()method to display the name and age information.

Code summary:

In this example, we create a Personclass that demonstrates how to define member variables, constructors, and member methods. By creating an Personobject and calling displayInfo()methods, we successfully display the object's name and age information. This example helped you understand the basic concepts of classes and objects and how to use them to organize and manipulate data.

Comprehensive exercises:

2. Create a class Rectanglewith two member variables, length and width, and a method calculateArea()for calculating the area of ​​the rectangle. Then create multiple Rectangleobjects and calculate their areas.

public class Rectangle {
    // 成员变量
    private double length;
    private double width;

    // 构造方法
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // 计算矩形的面积
    public double calculateArea() {
        return length * width;
    }

    public static void main(String[] args) {
        // 创建多个Rectangle对象并初始化
        Rectangle rectangle1 = new Rectangle(5.0, 4.0);
        Rectangle rectangle2 = new Rectangle(3.0, 7.0);
        Rectangle rectangle3 = new Rectangle(6.0, 2.5);

        // 计算并打印矩形的面积
        System.out.println("矩形1的面积:" + rectangle1.calculateArea());
        System.out.println("矩形2的面积:" + rectangle2.calculateArea());
        System.out.println("矩形3的面积:" + rectangle3.calculateArea());
    }
}

Code explanation:

  1. We have created a Rectangleclass called which has two member variables length(length) and width(width).

  2. In the constructor, we accept two parameters for initializing the member variables lengthand width.

  3. There is a calculateArea()member method named in the class which is used to calculate the area of ​​the rectangle length * widthi.e.

  4. In mainthe method, we create three Rectangleobjects and initialize their length and width through the constructor method.

  5. Finally, we call methods on each rectangle object calculateArea()to calculate and print the area of ​​the rectangle.

Code summary:

This example demonstrates how to create a Rectangleclass, define member variables and methods, and how to create multiple objects and use their methods to calculate the area of ​​a rectangle. This helps understand how classes and objects are used to organize and manipulate data in object-oriented programming.

1.2 Class

Basic exercises:

3. Create a class Carwith two member variables, brand and model, and a method startEngine()for starting the car engine. Then create an Carobject and call startEngine()the method.

public class Car {
    // 成员变量
    private String brand;
    private String model;

    // 构造方法
    public Car(String brand, String model) {
        this.brand = brand;
        this.model = model;
    }

    // 启动汽车引擎
    public void startEngine() {
        System.out.println("启动" + brand + " " + model + "的引擎");
    }

    public static void main(String[] args) {
        // 创建Car对象并初始化
        Car myCar = new Car("Toyota", "Camry");

        // 调用startEngine()方法来启动汽车引擎
        myCar.startEngine();
    }
}

Code explanation:

  1. Create a Carclass called, which has two member variables brand(brand) and model(model).

  2. In the constructor, it accepts two parameters for initializing member variables brandand model.

  3. There is a startEngine()member method named in the class which is used to start the car engine and display the startup information on the console.

  4. In mainthe method, create an Carobject myCarand initialize its make and model through the constructor method.

  5. Finally, the myCarobject's startEngine()methods are called to start the car's engine.

Code summary:

The example demonstrates how to create a Carclass, define member variables and methods, and how to create an object and call its methods to perform operations. It helps to understand how classes and objects are used in object-oriented programming to simulate real-world entities and behaviors.

Comprehensive exercises:

4. Create a class Circlewith a radius member variable and a method calculateArea()for calculating the area of ​​a circle. Then create multiple Circleobjects and calculate their areas.

public class Circle {
    // 成员变量
    private double radius;

    // 构造方法
    public Circle(double radius) {
        this.radius = radius;
    }

    // 计算圆的面积
    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    public static void main(String[] args) {
        // 创建多个Circle对象并初始化
        Circle circle1 = new Circle(3.0);
        Circle circle2 = new Circle(5.0);
        Circle circle3 = new Circle(2.5);

        // 计算并打印圆的面积
        System.out.println("圆1的面积:" + circle1.calculateArea());
        System.out.println("圆2的面积:" + circle2.calculateArea());
        System.out.println("圆3的面积:" + circle3.calculateArea());
    }
}

Code explanation:

  1. Create a Circleclass called, which has one member variable radius(radius).

  2. In the constructor, a parameter is accepted to initialize the member variables radius.

  3. calculateArea()There is a member method named in the class which is used to calculate the area of ​​a circle Math.PI * radius * radiusi.e.

  4. In mainthe method, create three Circleobjects representing circles with different radii, and initialize their radii through the constructor method.

  5. Finally, each circle object's calculateArea()methods are called to calculate and print the circle's area.

Code summary:

The example demonstrates how to create a Circleclass, define member variables and methods, and how to create multiple objects and call their methods to perform operations. It helps to understand how classes and objects are used in object-oriented programming to simulate real-world entities and behaviors.

1.3 Class construction method

Basic exercises:

4. Create a class Bookwith two member variables: book title and author, and a constructor with parameters to initialize these two member variables. Then create multiple Bookobjects and initialize their properties.

public class Book {
    // 成员变量
    private String title;
    private String author;

    // 带参数的构造方法
    public Book(String title, String author) {
        this.title = title;
        this.author = author;
    }

    public static void main(String[] args) {
        // 创建多个Book对象并初始化
        Book book1 = new Book("Java Programming", "John Smith");
        Book book2 = new Book("Python Basics", "Alice Johnson");
        Book book3 = new Book("C++ Fundamentals", "David Brown");

        // 打印书籍信息
        System.out.println("书籍1:" + book1.title + ",作者:" + book1.author);
        System.out.println("书籍2:" + book2.title + ",作者:" + book2.author);
        System.out.println("书籍3:" + book3.title + ",作者:" + book3.author);
    }
}

Code explanation:

  1. Create a Bookclass called, which has two member variables title(book title) and author(author).

  2. In the constructor, it accepts two parameters for initializing member variables titleand author.

  3. In mainthe method, three Bookobjects are created, each representing a book, and their title and author are initialized through the constructor method.

  4. Finally, print information about each book, including the title and author.

Code summary:

The example demonstrates how to create a Bookclass, define member variables and a constructor method with parameters, and how to create multiple objects and initialize their properties. It helps to understand how classes and objects are used in object-oriented programming to simulate real-world entities and behaviors.

Comprehensive exercises:

  1. Create a class Employeewith three member variables: name, job number, and salary, and a constructor with parameters to initialize these member variables. Then create multiple Employeeobjects and initialize their properties.
public class Employee {
    // 成员变量
    private String name;
    private int employeeId;
    private double salary;

    // 带参数的构造方法
    public Employee(String name, int employeeId, double salary) {
        this.name = name;
        this.employeeId = employeeId;
        this.salary = salary;
    }

    public static void main(String[] args) {
        // 创建多个Employee对象并初始化
        Employee employee1 = new Employee("John Smith", 101, 50000.0);
        Employee employee2 = new Employee("Alice Johnson", 102, 60000.0);
        Employee employee3 = new Employee("David Brown", 103, 55000.0);

        // 打印员工信息
        System.out.println("员工1:" + employee1.name + ",工号:" + employee1.employeeId + ",薪水:" + employee1.salary);
        System.out.println("员工2:" + employee2.name + ",工号:" + employee2.employeeId + ",薪水:" + employee2.salary);
        System.out.println("员工3:" + employee3.name + ",工号:" + employee3.employeeId + ",薪水:" + employee3.salary);
    }
}

Code explanation:

  1. Create a Employeeclass named, which has three member variables name(name), employeeId(employee number) and salary(salary).

  2. In the constructor, three parameters are accepted for initializing member variables name, employeeIdand salary.

  3. In mainthe method, three Employeeobjects are created, each object represents an employee, and their name, job number and salary are initialized through the constructor method.

  4. Finally, print each employee's information, including name, job number, and salary.

Code summary:

The example demonstrates how to create a Employeeclass, define member variables and a constructor method with parameters, and how to create multiple objects and initialize their properties. It helps to understand how classes and objects are used in object-oriented programming to simulate real-world entities and behaviors.

1.4 Static variables and static methods

Basic exercises:

7. Create a class MathOperationswith static methods add()and subtract()for performing addition and subtraction operations. mainThese static methods are then called within the method.

public class MathOperations {
    // 静态方法:加法
    public static int add(int a, int b) {
        return a + b;
    }

    // 静态方法:减法
    public static int subtract(int a, int b) {
        return a - b;
    }

    public static void main(String[] args) {
        // 调用add()方法进行加法操作
        int sum = MathOperations.add(10, 5);
        System.out.println("10 + 5 = " + sum);

        // 调用subtract()方法进行减法操作
        int difference = MathOperations.subtract(20, 8);
        System.out.println("20 - 8 = " + difference);
    }
}

Code explanation:

  1. Create a MathOperationsclass called that has two static methods: add()for addition operations and subtract()for subtraction operations.

  2. The static method add()accepts two integer parameters aand bperforms the addition and returns the result.

  3. The static method subtract()accepts two integer parameters aand bperforms the subtraction and returns the result.

  4. In the method, the static methods of the class and mainare called to perform addition and subtraction operations and print the results to the console.MathOperationsadd()subtract()

Code summary:

The example demonstrates how to create a MathOperationsclass, define static methods to perform addition and subtraction operations, and how to maincall these static methods within the method. Static methods can be used without creating an object to perform common operations. This helps understand how to use static methods to organize and execute code.

Comprehensive exercises:

7. Create a class Productwith three member variables: product name, price and inventory quantity, as well as static variables totalProductsfor tracking the total product quantity. Write constructor methods to initialize member variables and update them every time a new object is created totalProducts.

public class Product {
    // 成员变量
    private String productName;
    private double price;
    private int quantity;

    // 静态变量:总商品数量
    private static int totalProducts = 0;

    // 带参数的构造方法
    public Product(String productName, double price, int quantity) {
        this.productName = productName;
        this.price = price;
        this.quantity = quantity;
        totalProducts++; // 每次创建新对象时更新总商品数量
    }

    public static void main(String[] args) {
        // 创建多个Product对象并初始化
        Product product1 = new Product("Laptop", 899.99, 10);
        Product product2 = new Product("Smartphone", 499.99, 20);

        // 打印商品信息和总商品数量
        System.out.println("商品1:" + product1.productName + ",价格:" + product1.price + ",库存数量:" + product1.quantity);
        System.out.println("商品2:" + product2.productName + ",价格:" + product2.price + ",库存数量:" + product2.quantity);

        System.out.println("总商品数量:" + Product.totalProducts);
    }
}

Code explanation:

  1. Create a Productclass named, which has three member variables productName(product name), price(price) and quantity(inventory quantity).

  2. Static variable totalProductsis used to track the total item quantity and is updated every time a new object is created.

  3. The constructor with parameters accepts the product name, price and inventory quantity, which is used to initialize member variables and increments in the constructor totalProductsto update the total product quantity.

  4. In mainthe method, we create two Productobjects, each representing a commodity, and initialize their properties through the constructor method.

  5. Finally, print the information of each product and the total product quantity.

Code summary:

The example demonstrates how to create a Productclass, define member variables and static variables, and how to update the static variables in the constructor to track the total item quantity. It helps to understand how to use static variables to share data and state.

Comprehensive exercises:

Design a simple student management system, including the following requirements:

  1. Create a Studentclass that includes the student's name, age, and grade as member variables.

  2. StudentCreate a constructor for the class that initializes the student's name, age, and grade.

  3. Create a Schoolclass for managing student information. SchoolThe class should include an array (or collection) that stores student objects.

  4. SchoolThe class should provide the following functionality:

    • Add students: Ability to add new student information to the school.
    • Find students: Able to find student information based on their names and display it.
    • Display all student information: Ability to list the names, ages, and grades of all students in the school.
  5. In mainthe method, create an Schoolobject and simulate adding multiple student information, and then test the functions of finding students and displaying all student information.

hint:

  • StudentClasses and classes need to be created School, along with appropriate member variables and methods.
  • Use an array or collection to store student information.
  • In mainthe method, create Schoolthe object and simulate adding student information, then test your functionality.
import java.util.ArrayList;

// 学生类
class Student {
    private String name;
    private int age;
    private double score;

    // 构造方法
    public Student(String name, int age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    // 获取学生姓名
    public String getName() {
        return name;
    }

    // 显示学生信息
    public void displayInfo() {
        System.out.println("姓名: " + name + ", 年龄: " + age + ", 成绩: " + score);
    }
}

// 学校类
class School {
    private ArrayList<Student> students = new ArrayList<>();

    // 添加学生
    public void addStudent(Student student) {
        students.add(student);
    }

    // 查找学生
    public Student findStudentByName(String name) {
        for (Student student : students) {
            if (student.getName().equals(name)) {
                return student;
            }
        }
        return null; // 如果找不到返回null
    }

    // 显示所有学生信息
    public void displayAllStudents() {
        System.out.println("学校所有学生信息:");
        for (Student student : students) {
            student.displayInfo();
        }
    }
}

public class StudentManagementSystem {
    public static void main(String[] args) {
        // 创建学校对象
        School school = new School();

        // 模拟添加学生信息
        school.addStudent(new Student("Alice", 18, 95.5));
        school.addStudent(new Student("Bob", 19, 88.0));
        school.addStudent(new Student("Charlie", 20, 92.5));

        // 测试查找学生和显示所有学生信息功能
        Student foundStudent = school.findStudentByName("Bob");
        if (foundStudent != null) {
            System.out.println("查找到的学生信息:");
            foundStudent.displayInfo();
        } else {
            System.out.println("未找到该学生!");
        }

        school.displayAllStudents();
    }
}

explain:

  1. Created a Studentclass that included the student's name, age, and grades as member variables and provided a constructor method and a method for displaying student information.

  2. Created a Schoolclass that ArrayListstores student objects and provides methods to add students, find students, and display all student information.

  3. In mainthe method, we create an Schoolobject and simulate adding multiple student information. We then tested the ability to find students and display information about all students.

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132880239