Java抽象类练习

(1)、定义一个抽象类Weapon,该抽象类有两个抽象方法attack(),move():这两个方法分别表示武器的攻击和移动方式。
(2)、定义3个类:Tank,Flighter,WarShip都继承自Weapon,分别用不同的方式实现Weapon类中的抽象方法。

(3)、写一个类Army,代表一支军//队,这个类有一个属性是Weapon数组w(用来存储该军//队所拥有的所有武器);

该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量,
并用这一大小来初始化数组w。在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。

(4)、写一个主方法去测试以上程序。

分析:

大致的都会,就是对题目的理解不到位,不知道数组的初始化应该怎样实现,所以利用随机数生成来初始化数组。


 

import java.util.*;//生成随机数对Weapon数组w进行初始化
abstract class Weapon{
	abstract void attack();
	
	
	abstract void move();
}

class Tank extends Weapon{
	public void attack(){
	System.out.println("A tank is attacking!");
	}
	
	public void move(){
	System.out.println("A tank is moving!");
	}
}

public class Flighter extends Weapon{
	public void attack(){
	System.out.println("A Flighter is attacking!");
	}
	
	public void move(){
	System.out.println("A Flighter is moving!");
	}
}
	
class WarShip extends Weapon{
	public void attack(){
	System.out.println("A WarShip is attacking!");
	}
	
	public void move(){
	System.out.println("A WarShip is moving!");
	}
}

class Army{
	Weapon w[];
	
	public Army(int x){
		w = new Weapon[x];
		Random rand =new Random();
		for(int i=0;i<w.length;i++)
		{
			switch(rand.nextInt(3)){
				case 0:
				w[i]=new Tank();
				break;
				case 1:
				w[i]=new Flighter();
				break;
				case 2:
				w[i]=new WarShip();
				break;
			}
			
		}
		}
		
		public void attackAll(){
			for(Weapon i : w){
				i.attack();
				}
			}
			
			public void moveAll(){
				for(Weapon j : w){
					j.move();
					}
				}
	}	
	
class TestWeapon{
	public static void main(String args[]){
		Army a1 = new Army(10);

		a1.attackAll();
		a1.moveAll();
		}
	}

 

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值