接口/抽象类

接口:相当于一种属性,能力,将该种属性赋予各种类。接口里包括各种成员方法,使用该接口的类必须强制执行。

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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值