Java对数组对象进行排序&JAVA中implements实现多接口

下面是一组对数组对象进行排序的代码:

复制代码
package com.sun;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Test09 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Dog dog[] = new Dog[3];
         dog[0]= new Dog("wangchai",10);
         dog[1]= new Dog("laifu",9);
         dog[2]= new Dog("ww",20);
        Arrays.sort(dog);

        for(int i=0;i<dog.length;i++){
            System.out.println(dog[i].name);
        }
    }

}
class Dog implements  Comparable{
    public Integer tizhong = 0;
    public String name = "";
    public Dog(String name, int tizhong) {
        this.name = name;
        this.tizhong = tizhong;
    }
    //按年龄排序
    @Override
    //如果先按数字再按字符排序,则这样写:
     public int compareTo(Object o)
      {
        Dog s=(Dog)o;
             int result= tizhong>s.tizhong?1:(tizhong==s.tizhong?0:-1);
              if (0==result){
                  result=name.compareTo(s.name);
               }
             return result;
      }
}

JAVA中implements实现多接口
这里有一个游戏,人猿泰山。 主角是一个单独的类,这里我们主要用怪物说明接口的用法: 怪物有很多种, 按地域分:有的在天上飞,有的在地上跑,有的在水里游 按攻击方式分:有的能近距离物理攻击,有的能远距离射击

假设游戏里需要这样的几种怪—— 
野狗:地上移动,近距离攻击 
黑熊:地上移动,近/远距离攻击 
秃鹫:地上/天上移动,远距离攻击 
食人鱼:水中移动,近距离攻击 
鳄鱼:地上/水中移动,近距离攻击

显然,如果我们将每一种怪物定义为一个类,那就不是面向对象的程序开发了,我们应当使用接口: 
interface OnEarth{//陆地接口 
int earthSpeed;//陆地移动速度 
void earthMove();//陆地移动方法 
}

interface OnWater{//水中接口 
int waterSpeed;//水中移动速度 
void waterMove();//水中移动方法 
}

interface OnAir{//空中接口 
int airSpeed;//水中移动速度 
void airMove();//水中移动方法 
}

interface NearAttack{//近距离攻击接口 
int nearAttackPower;//近距离攻击力 
void nearAttack();//近距离攻击方法 
}

interface FarAttack{//远距离攻击接口 
int farAttackPower;//远距离攻击力 
void farAttack();//远距离攻击方法 
}

这样一来,根据需求,我们可以选择性的继承接口: 
class Tyke implements OnEarth, NearAttack{//野狗类 
void earthMove(){//实现继承的方法1 

void nearAttack(){//实现继承的方法2 

}

class BlackBear implements OnEarth, NearAttack, FarAttack{//黑熊类 
void earthMove(){//实现继承的方法1 

void nearAttack(){//实现继承的方法2 

void farAttack(){//实现继承的方法3 

}

class Vulture implements OnEarth, OnAir, FarAttack{//秃鹫类 
void earthMove(){//实现继承的方法1 

void airMove(){//实现继承的方法2 

void farAttack(){//实现继承的方法3 

}

class ManeatFish implements OnWater, NearAttack{//食人鱼类 
void waterMove(){//实现继承的方法1 

void nearAttack(){//实现继承的方法2 

}

class Crocodile implements OnEarth, OnWater, NearAttack{//鳄鱼类 
void earthMove(){//实现继承的方法1 

void waterMove(){//实现继承的方法2 

void nearAttack(){//实现继承的方法3 

}

在实现接口方法的同时,也拥有了接口中定义的成员变量,这样就构成了一个有机的整体,使整个程序既体现了类的多样性,又不失结构组合的灵活性,且需要在某个特性增加其他功能,只要修改接口就可以了,其继承的类自动修改。


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/hgch95/archive/2009/09/15/4556119.aspx

猜你喜欢

转载自blog.csdn.net/u012530451/article/details/80875086