展开全部
主要思路;。创建父类子类你自己看着敲进去,比较e5a48de588b63231313335323631343130323136353331333361323031简单。
每个函数都要有一个带参数的构造函数;当数组中的参数传入时可以对子类对象初始化。
最后比较排序我是用另一个数组接收原数组元素(对象)中的getWeight() 方法的返回值用于排序,然后在找到对应的值打出来就能达到你要的效果了。
父类:
package playgame;
public abstract class Pet {
private String name;
private int age;
private double weight;
public void getInformation(String name,int age,double weight){
this.name=name;
this.age=age;
this.weight=weight;
}
public double getWeight(){
return weight;
}
public String toString(){
String str="name="+name+",age="+age+",weight"+weight;
return str;
}
public abstract void speak();
public abstract void eat();
}
package playgame;
public class Bird extends Pet{
private String name;
private double weight;
private double flyspeed;
public Bird(String name,double flyspeed,double weight){
this.name=name;
this.flyspeed=flyspeed;
this.weight=weight;
}
public double getWeight(){
return weight;
}
public void speak(){
System.out.println("我是一只小小鸟");
}
public void eat(){
System.out.println("我最爱吃虫子");
}
public String toString(){
String str="name="+name+",flyspeed="+flyspeed+",weight="+weight;
return str;
}
}
package playgame;
public class Cat extends Pet {
private String name;
private String coulour;
private double weight;
public Cat(String name,String coulour,double weight){
this.name=name;
this.coulour=coulour;
this.weight=weight;
}
public double getWeight(){
return weight;
}
public void speak() {
System.out.println("我是一只猫");
}
public void eat() {
System.out.println("我爱吃鱼");
}
public String toString(){
String str="name="+name+",coulour="+coulour+",weight="+weight;
return str;
}
}
package playgame;
public class Dog extends Pet {
private String name;
private double weight;
private String variety;
public Dog(String name,String variety,double weight){
this.name=name;
this.variety=variety;
this.weight=weight;
}
public double getWeight(){
return weight;
}
public void speak() {
System.out.println("我是一只狗");
}
public void eat() {
System.out.println("我爱吃骨头");
}
public String toString(){
String str="name="+name+",weight="+weight+",variety="+variety;
return str;
}
}
package playgame;
import java.util.Arrays;
public class Text1 {
public static void main(String[] args) {
Pet arr[]={new Dog("狗","藏獒",180000.5),new Dog("狗","藏獒",180006.5),
new Cat("猫","红色",18000.5),new Cat("猫","黑色",18000.5),
new Bird("鸟",20.5,180),new Bird("鸟",22.5,187)};
double arr1[]=new double[6];
for(int i=0;i<6;i++){
arr1[i]=arr[i].getWeight();
}
Arrays.sort(arr1);
for(int i=0;i<6;i++){
for(int j=0;j<6;j++){
if(arr1[i]==arr[j].getWeight()){
System.out.println(arr[j].toString()+"\t");
break;
}
}
}
}
}
最后面这个是主函数的类。。请他三个子类在中间,有不明白的地方在追问。