Design a Product class that includes the properties of product’s ID, price, number of sold (當噺的沌噽). The class has the following operations: 1. Revenue: calculates the total revenue (噷當噺噻) of all products. 2. toString: returns the values of all the attributes of a Prodect object. 3. Output: output the product information by using toString(). Requirement: 1. The class must have a constructor with parameters; 2. Write a test program that declares three objects. One of these objects is declared by using your student No (学噼) as product‘s ID.
时间: 2024-02-26 11:54:15 浏览: 254
下面是一个符合要求的Java代码实现:
```java
public class Product {
private String ID;
private double price;
private int quantitySold;
public Product(String ID, double price, int quantitySold) {
this.ID = ID;
this.price = price;
this.quantitySold = quantitySold;
}
public double revenue() {
return price * quantitySold;
}
public String toString() {
return "Product ID: " + ID + ", Price: " + price + ", Quantity Sold: " + quantitySold;
}
public static void main(String[] args) {
Product p1 = new Product("12345", 19.99, 100);
Product p2 = new Product("67890", 29.99, 50);
Product p3 = new Product("2021123456", 9.99, 200);
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println(p3.toString());
}
}
```
在main方法中,我们创建了三个Product对象,其中一个的ID是学号。然后我们调用了每个对象的toString方法来打印出它们的属性信息。运行上述代码,输出结果如下:
```
Product ID: 12345, Price: 19.99, Quantity Sold: 100
Product ID: 67890, Price: 29.99, Quantity Sold: 50
Product ID: 2021123456, Price: 9.99, Quantity Sold: 200
```
阅读全文