java创建一个房屋类,其中包含私有属性地址积租金,然后创建 方法去访问和修改这些属性的测试类
时间: 2024-05-16 15:12:51 浏览: 9
下面是一个Java创建房屋类的示例代码,其中包含私有属性地址、租金:
```java
public class House {
private String address;
private double rent;
public House(String address, double rent) {
this.address = address;
this.rent = rent;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getRent() {
return rent;
}
public void setRent(double rent) {
this.rent = rent;
}
}
```
上述代码中,我们创建了一个名为 `House` 的类,并在其内部定义了两个私有属性 `address` 和 `rent`,分别表示房屋的地址和租金。然后,我们又定义了两个公有方法 `getAddress()` 和 `getRent()`,用于获取 `address` 和 `rent` 的值,以及两个公有方法 `setAddress()` 和 `setRent()`,用于修改 `address` 和 `rent` 的值。
下面是一个测试类的示例代码,用于测试上述 `House` 类的方法:
```java
public class HouseTest {
public static void main(String[] args) {
House house = new House("No.123, Beijing Road", 2000.0);
System.out.println("Address: " + house.getAddress());
System.out.println("Rent: " + house.getRent());
house.setAddress("No.456, Shanghai Road");
house.setRent(2500.0);
System.out.println("Address: " + house.getAddress());
System.out.println("Rent: " + house.getRent());
}
}
```
上述代码中,我们首先创建了一个 `House` 对象,并为其传入地址和租金的初始值。然后,我们分别调用了 `getAddress()` 和 `getRent()` 方法获取其地址和租金,并输出到控制台中。接下来,我们又分别调用了 `setAddress()` 和 `setRent()` 方法修改了其地址和租金的值,并再次调用 `getAddress()` 和 `getRent()` 方法获取修改后的值,并输出到控制台中。最终,我们可以在控制台中看到修改后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)