Java,编写一个类Test04_1.java,实例化1个Phone类,自定义它的品牌和价格(注意使用set方法赋值),然后调用detail()方法进行输出
时间: 2024-05-12 11:20:37 浏览: 41
```
public class Test04_1 {
public static void main(String[] args) {
Phone phone = new Phone();
phone.setBrand("Apple");
phone.setPrice(7999);
phone.detail();
}
}
class Phone {
private String brand;
private double price;
public void setBrand(String brand) {
this.brand = brand;
}
public void setPrice(double price) {
this.price = price;
}
public void detail() {
System.out.println("品牌:" + brand);
System.out.println("价格:" + price);
}
}
```
相关问题
定义一个手机类(Phone)和一个手机测试类(PhoneTest),具体要求如下: (1)Phone类包含3个私有实例属性: brand(品牌,字符串类型),color(颜色,字符串类型),price(价格,浮点数类型);编写类的初始化方法对其属性进行初始化 (2)编写所有属性的Getters和Setters方法; (3)构建一个手机对象,并输出以下信息 “品牌:HUAWEI nova 11,颜色:雪域白价格:2499.00”到控制台。
下面是一个符合要求的Java代码示例:
```
public class Phone {
private String brand;
private String color;
private float price;
public Phone(String brand, String color, float price) {
this.brand = brand;
this.color = color;
this.price = price;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
public class PhoneTest {
public static void main(String[] args) {
Phone phone = new Phone("HUAWEI nova 11", "雪域白", 2499.00f);
System.out.println("品牌:" + phone.getBrand() + ", 颜色:" + phone.getColor() + ", 价格:" + phone.getPrice());
}
}
```
运行结果如下:
```
品牌:HUAWEI nova 11, 颜色:雪域白, 价格:2499.0
```
用python定义一个手机类(Phone)和一个手机测试类(PhoneTest),具体要求如下: (1)Phone类包含3个私有实例属性: brand(品牌,字符串类型),color(颜色,字符串类型),price(价格,浮点数类型);编写类的初始化方法对其属性进行初始化 (2)编写所有属性的Getters和Setters方法; (3)构建一个手机对象,并输出以下信息 “品牌:HUAWEI nova 11,颜色:雪域白价格:2499.00”到控制台。
下面是一个符合要求的Python代码示例:
```
class Phone:
def __init__(self, brand, color, price):
self.__brand = brand
self.__color = color
self.__price = price
def get_brand(self):
return self.__brand
def set_brand(self, brand):
self.__brand = brand
def get_color(self):
return self.__color
def set_color(self, color):
self.__color = color
def get_price(self):
return self.__price
def set_price(self, price):
self.__price = price
class PhoneTest:
def main(self):
phone = Phone("HUAWEI nova 11", "雪域白", 2499.00)
print("品牌:" + phone.get_brand() + ", 颜色:" + phone.get_color() + ", 价格:" + format(phone.get_price(), ".2f"))
PhoneTest().main()
```
运行结果如下:
```
品牌:HUAWEI nova 11, 颜色:雪域白, 价格:2499.00
```
阅读全文