类中有属性:carName String,carType String,carprice Double,carcount Integer,carDate Date,封装这个类,重写toString()方法和equals()方法
时间: 2024-04-22 20:27:55 浏览: 134
可以封装一个名为`Car`的类,该类包含属性`carName`、`carType`、`carPrice`、`carCount`和`carDate`。以下是一个示例实现:
```java
import java.util.Date;
public class Car {
private String carName;
private String carType;
private Double carPrice;
private Integer carCount;
private Date carDate;
public Car(String carName, String carType, Double carPrice, Integer carCount, Date carDate) {
this.carName = carName;
this.carType = carType;
this.carPrice = carPrice;
this.carCount = carCount;
this.carDate = carDate;
}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getCarType() {
return carType;
}
public void setCarType(String carType) {
this.carType = carType;
}
public Double getCarPrice() {
return carPrice;
}
public void setCarPrice(Double carPrice) {
this.carPrice = carPrice;
}
public Integer getCarCount() {
return carCount;
}
public void setCarCount(Integer carCount) {
this.carCount = carCount;
}
public Date getCarDate() {
return carDate;
}
public void setCarDate(Date carDate) {
this.carDate = carDate;
}
@Override
public String toString() {
return "Car{" +
"carName='" + carName + '\'' +
", carType='" + carType + '\'' +
", carPrice=" + carPrice +
", carCount=" + carCount +
", carDate=" + carDate +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
if (!carName.equals(car.carName)) return false;
if (!carType.equals(car.carType)) return false;
if (!carPrice.equals(car.carPrice)) return false;
if (!carCount.equals(car.carCount)) return false;
return carDate.equals(car.carDate);
}
@Override
public int hashCode() {
int result = carName.hashCode();
result = 31 * result + carType.hashCode();
result = 31 * result + carPrice.hashCode();
result = 31 * result + carCount.hashCode();
result = 31 * result + carDate.hashCode();
return result;
}
}
```
这个`Car`类包含了构造方法用于初始化属性,以及各个属性的getter和setter方法。重写了`toString()`方法,可以将对象转换为字符串表示。重写了`equals()`方法,用于比较两个对象是否相等。
你可以根据需要创建`Car`对象,并使用相应的方法进行属性的访问和操作。例如:
```java
Car car = new Car("BMW", "Sedan", 50000.0, 10, new Date());
System.out.println(car.toString());
```
这将打印出`Car`对象的字符串表示。你还可以使用`equals()`方法来比较两个`Car`对象是否相等。
阅读全文