Java中定义Phone类,有品牌,颜色,价格属性,价格范围在200~8000,有打电话发短信的方法,创建对象输出Phone所有信息
时间: 2023-08-08 22:06:31 浏览: 196
Phone.java
下面是Java中Phone类的定义:
```java
public class Phone {
private String brand;
private String color;
private int price;
public Phone(String brand, String color, int price) {
this.brand = brand;
this.color = color;
if (price < 200 || price > 8000) {
throw new IllegalArgumentException("Price must be between 200 and 8000");
}
this.price = price;
}
public void call(String number) {
System.out.println("Calling " + number + " with " + brand + " phone");
}
public void sendMessage(String message, String number) {
System.out.println("Sending message '" + message + "' to " + number + " with " + brand + " phone");
}
public String getBrand() {
return brand;
}
public String getColor() {
return color;
}
public int getPrice() {
return price;
}
@Override
public String toString() {
return "Phone [brand=" + brand + ", color=" + color + ", price=" + price + "]";
}
}
```
我们在构造方法中对价格进行了范围限制,如果不在200~8000的范围内,则抛出IllegalArgumentException异常。
在类中定义了打电话和发短信的方法。我们使用toString()方法来输出Phone类的所有信息。
下面是创建对象并输出所有信息的示例:
```java
public class Main {
public static void main(String[] args) {
Phone myPhone = new Phone("Apple", "White", 5000);
System.out.println(myPhone);
myPhone.call("123456789");
myPhone.sendMessage("Hello!", "123456789");
}
}
```
输出结果为:
```
Phone [brand=Apple, color=White, price=5000]
Calling 123456789 with Apple phone
Sending message 'Hello!' to 123456789 with Apple phone
```
阅读全文