/定义一个电脑品牌枚举类,其中只有Lenovo、Dell、Acer、Apple四个电脑品牌。要求该类中: //1)含有两个私有属性:name,price,并有对应的set、get方法; //2)含有一个无参构造方法和一个能给两个属性赋值的有参构造方法,并要求两个枚举对象有属性值,两个枚举对象无属性值; //3)重写toString()方法,输出name和price; //4)定义测试类,输出所有枚举值(用values())并给无属性值的枚举对象赋值并输出。
时间: 2024-01-12 14:02:44 浏览: 33
好的,以下是代码实现:
```java
public enum ComputerBrand {
LENOVO("Lenovo"),
DELL("Dell"),
ACER("Acer"),
APPLE("Apple", 10000);
private String name;
private int price;
ComputerBrand(String name) {
this.name = name;
}
ComputerBrand(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public String toString() {
return "ComputerBrand{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
```
测试类:
```java
public class EnumTest {
public static void main(String[] args) {
for (ComputerBrand computerBrand : ComputerBrand.values()) {
System.out.println(computerBrand.toString());
}
ComputerBrand.APPLE.setPrice(15000);
System.out.println(ComputerBrand.APPLE.toString());
}
}
```
输出结果:
```
ComputerBrand{name='Lenovo', price=0}
ComputerBrand{name='Dell', price=0}
ComputerBrand{name='Acer', price=0}
ComputerBrand{name='Apple', price=10000}
ComputerBrand{name='Lenovo', price=0}
ComputerBrand{name='Dell', price=0}
ComputerBrand{name='Acer', price=0}
ComputerBrand{name='Apple', price=15000}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)