java分别通过无参构造方法和带参构造方法,完成对象实例化实例化对象,并打印输出对象信息,输出格式如效果图。 效果图: 我是使用无参构造产生的猴子: 名称:长尾猴 特征:尾巴长 我是使用带参构造产生的猴子: 名称:白头叶猴 特征:头上有白毛,喜欢吃树叶
时间: 2023-05-22 11:02:14 浏览: 65
好的,让我来回答你的问题。以下是使用无参构造方法和带参构造方法实例化对象并输出对象信息的Java代码:
使用无参构造方法:
```
public class Monkey {
private String name;
private String feature;
public Monkey() {
this.name = "长尾猴";
this.feature = "尾巴长";
}
public void printInfo() {
System.out.println("我是使用无参构造产生的猴子:");
System.out.println("名称:" + this.name);
System.out.println("特征:" + this.feature);
}
}
// 在主函数中调用
Monkey monkey = new Monkey();
monkey.printInfo();
```
使用带参构造方法:
```
public class Monkey {
private String name;
private String feature;
public Monkey(String name, String feature) {
this.name = name;
this.feature = feature;
}
public void printInfo() {
System.out.println("我是使用带参构造产生的猴子:");
System.out.println("名称:" + this.name);
System.out.println("特征:" + this.feature);
}
}
// 在主函数中调用
Monkey monkey = new Monkey("白头叶猴", "头上有白毛,喜欢吃树叶");
monkey.printInfo();
```
希望这个回答能够帮助到你!
相关推荐
![](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)