接口:相当于一种属性,能力,将该种属性赋予各种类。接口里包括各种成员方法,使用该接口的类必须强制执行。
public class First {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("This is the very first code.");
petsArray();
}
public static void petsArray()
{
Dog[] dogs=new Dog[10];
Cat[] cats=new Cat[12];
for(int i=0;i<dogs.length;i++)
dogs[i]=new Dog();
for(int i=0;i<cats.length;i++)
cats[i]=new Cat();
petsSort(dogs);
petsSort(cats);
System.out.println("Dogs-----------------------");
for(int i=0;i<dogs.length;i++)
{
System.out.print((i+1)+":");
dogs[i].print();
System.out.println();
}
System.out.println("Cats-----------------------");
for(int i=0;i<cats.length;i++)
{
System.out.print((i+1)+":");
cats[i].print();
System.out.println();
}
}
public static void petsSort(Compare[] array)
{
Compare temp;
for(int i=0;i<array.length-1;i++)
for(int j=i+1;j<array.length;j++)
{
if(array[i].compareTo(array[j]))
{
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
}
class Animal//也可以使用父类子类继承,通过重写父类的方法,达成接口的目的,但是父类的compareTo方法必须包含一些方法体,但这在本题中是无意义的
{
public int bodyWeight;
public int height;
public boolean comparTeTo(Animal animal)
{
return true;
}
}
/*
class Dog extends Animal
{
public boolean comparTeTo(Animal animal)
{
return true;
}
}
class Cat extends Animal
{
public boolean comparTeTo(Animal animal)
{
return true;
}
}*/
interface Compare
{
public boolean compareTo(Object obj);
public void print();
}
class Dog implements Compare
{
public int bodyWeight;
Dog()
{
bodyWeight=(int)(Math.random()*50+2);
}
public boolean compareTo(Object obj)//由于接口是要为各个类使用的,故只能写超级父类Object
{
Dog dog=(Dog)obj;//因此在重写该方法时,只能先拆箱,把Dog从Object中暴露出来
return bodyWeight>=dog.bodyWeight?true:false;
}
public void print()
{
System.out.print(bodyWeight);
}
}
class Cat implements Compare
{
public int height;
Cat()
{
height=(int)(Math.random()*20+2);
}
public boolean compareTo(Object obj)
{
//Cat cat=(Cat)obj;//????????????????
return height>=((Cat)obj).height?true:false;//???????????????
//return height>=cat.height?true:false;
}
public void print()
{
System.out.print(height);
}
}