1.6 Practice and Exercise
1.1 Overview of object-oriented
Basic exercises:
1. Create a class Person
with two member variables: name and age, and a method displayInfo()
for displaying name and age. Then create an Person
object 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:
-
We have created a
Person
class called which has two member variablesname
(name) andage
(age). -
In the constructor, we accept two parameters for initializing the member variables
name
andage
. -
There is a
displayInfo()
member method called in the class which is used to display the name and age. -
In
main
the method, we create anPerson
objectperson1
and initialize the name and age of the object through the constructor method. -
Finally, we call
person1
the object'sdisplayInfo()
method to display the name and age information.
Code summary:
In this example, we create a Person
class that demonstrates how to define member variables, constructors, and member methods. By creating an Person
object 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 Rectangle
with two member variables, length and width, and a method calculateArea()
for calculating the area of the rectangle. Then create multiple Rectangle
objects 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:
-
We have created a
Rectangle
class called which has two member variableslength
(length) andwidth
(width). -
In the constructor, we accept two parameters for initializing the member variables
length
andwidth
. -
There is a
calculateArea()
member method named in the class which is used to calculate the area of the rectanglelength * width
i.e. -
In
main
the method, we create threeRectangle
objects and initialize their length and width through the constructor method. -
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 Rectangle
class, 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 Car
with two member variables, brand and model, and a method startEngine()
for starting the car engine. Then create an Car
object 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:
-
Create a
Car
class called, which has two member variablesbrand
(brand) andmodel
(model). -
In the constructor, it accepts two parameters for initializing member variables
brand
andmodel
. -
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. -
In
main
the method, create anCar
objectmyCar
and initialize its make and model through the constructor method. -
Finally, the
myCar
object'sstartEngine()
methods are called to start the car's engine.
Code summary:
The example demonstrates how to create a Car
class, 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 Circle
with a radius member variable and a method calculateArea()
for calculating the area of a circle. Then create multiple Circle
objects 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:
-
Create a
Circle
class called, which has one member variableradius
(radius). -
In the constructor, a parameter is accepted to initialize the member variables
radius
. -
calculateArea()
There is a member method named in the class which is used to calculate the area of a circleMath.PI * radius * radius
i.e. -
In
main
the method, create threeCircle
objects representing circles with different radii, and initialize their radii through the constructor method. -
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 Circle
class, 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 Book
with two member variables: book title and author, and a constructor with parameters to initialize these two member variables. Then create multiple Book
objects 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:
-
Create a
Book
class called, which has two member variablestitle
(book title) andauthor
(author). -
In the constructor, it accepts two parameters for initializing member variables
title
andauthor
. -
In
main
the method, threeBook
objects are created, each representing a book, and their title and author are initialized through the constructor method. -
Finally, print information about each book, including the title and author.
Code summary:
The example demonstrates how to create a Book
class, 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:
- Create a class
Employee
with three member variables: name, job number, and salary, and a constructor with parameters to initialize these member variables. Then create multipleEmployee
objects 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:
-
Create a
Employee
class named, which has three member variablesname
(name),employeeId
(employee number) andsalary
(salary). -
In the constructor, three parameters are accepted for initializing member variables
name
,employeeId
andsalary
. -
In
main
the method, threeEmployee
objects are created, each object represents an employee, and their name, job number and salary are initialized through the constructor method. -
Finally, print each employee's information, including name, job number, and salary.
Code summary:
The example demonstrates how to create a Employee
class, 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 MathOperations
with static methods add()
and subtract()
for performing addition and subtraction operations. main
These 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:
-
Create a
MathOperations
class called that has two static methods:add()
for addition operations andsubtract()
for subtraction operations. -
The static method
add()
accepts two integer parametersa
andb
performs the addition and returns the result. -
The static method
subtract()
accepts two integer parametersa
andb
performs the subtraction and returns the result. -
In the method, the static methods of the class and
main
are called to perform addition and subtraction operations and print the results to the console.MathOperations
add()
subtract()
Code summary:
The example demonstrates how to create a MathOperations
class, define static methods to perform addition and subtraction operations, and how to main
call 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 Product
with three member variables: product name, price and inventory quantity, as well as static variables totalProducts
for 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:
-
Create a
Product
class named, which has three member variablesproductName
(product name),price
(price) andquantity
(inventory quantity). -
Static variable
totalProducts
is used to track the total item quantity and is updated every time a new object is created. -
The constructor with parameters accepts the product name, price and inventory quantity, which is used to initialize member variables and increments in the constructor
totalProducts
to update the total product quantity. -
In
main
the method, we create twoProduct
objects, each representing a commodity, and initialize their properties through the constructor method. -
Finally, print the information of each product and the total product quantity.
Code summary:
The example demonstrates how to create a Product
class, 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:
-
Create a
Student
class that includes the student's name, age, and grade as member variables. -
Student
Create a constructor for the class that initializes the student's name, age, and grade. -
Create a
School
class for managing student information.School
The class should include an array (or collection) that stores student objects. -
School
The 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.
-
In
main
the method, create anSchool
object and simulate adding multiple student information, and then test the functions of finding students and displaying all student information.
hint:
Student
Classes and classes need to be createdSchool
, along with appropriate member variables and methods.- Use an array or collection to store student information.
- In
main
the method, createSchool
the 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:
-
Created a
Student
class that included the student's name, age, and grades as member variables and provided a constructor method and a method for displaying student information. -
Created a
School
class thatArrayList
stores student objects and provides methods to add students, find students, and display all student information. -
In
main
the method, we create anSchool
object and simulate adding multiple student information. We then tested the ability to find students and display information about all students.