优化下面代码 Mouse m=new Mouse("jack",5,"red",5.5); Dog d=new Dog("xiaobai",4,"white",3.5);
时间: 2023-07-06 21:04:12 浏览: 72
可以考虑使用对象数组来存储多个对象,避免代码重复。具体修改如下:
```
Animal[] animals = new Animal[2];
animals[0] = new Mouse("jack", 5, "red", 5.5);
animals[1] = new Dog("xiaobai", 4, "white", 3.5);
```
这样就可以通过循环遍历 `animals` 数组来访问每个对象的属性和方法。
相关问题
public class Student{ private int id; private String name; public Student(int id,String name){ this.id = id; this.name = name; } } public static void main(String[] args) { Set<Student> set = new TreeSet<>(); set.add(new Student(1,"xiaohei")); set.add(new Student(2,"xiaobai")); System.out.println(set.size()); }
这段代码创建了一个Student类,包含id和name属性以及一个构造方法。在主函数中,创建了一个TreeSet类型的set对象,用于存储Student对象,并向其中添加了两个Student对象。最后输出set的大小。
需要注意的是,由于Student类没有实现Comparable接口或提供Comparator比较器,因此在添加Student对象时,TreeSet无法确定它们之间的顺序。因此,当执行set.size()时,可能会抛出ClassCastException异常,提示无法将Student对象转换为java.lang.Comparable。为了解决这个问题,可以让Student类实现Comparable接口,并重写compareTo方法,或者在创建TreeSet对象时提供一个Comparator比较器。
#include<iostream> using namespace std; /* 根据上下文,特别是16,21,28行代码,修改以下代码,使之正常输出 */ struct Person { char name[16]; int age; } /*** int main() { per a; strcpy(a.name, "xiaomi"); a.age = 7; cout<<a.name<<" "<<a.age<<endl; //------------------------------------// per *q; q = new Person[sizeof(struct Person)]; strcpy(q->name, "xiaobai"); q->age = 8; cout<<q->name<<" "<<q->age<<endl; delete q; //------------------------------------// perptr p; p = new Person[sizeof(struct Person)]; strcpy(p->name, "xiaotao"); p->age = 9; cout<<p->name<<" "<<p->age<<endl; delete p; return 0; } **/
#include<iostream>
#include<cstring>
using namespace std;
struct Person {
char name[16];
int age;
};
int main() {
Person a;
strcpy(a.name, "xiaomi");
a.age = 7;
cout<<a.name<<" "<<a.age<<endl;
Person *q;
q = new Person;
strcpy(q->name, "xiaobai");
q->age = 8;
cout<<q->name<<" "<<q->age<<endl;
delete q;
Person *p;
p = new Person;
strcpy(p->name, "xiaotao");
p->age = 9;
cout<<p->name<<" "<<p->age<<endl;
delete p;
return 0;
}
阅读全文