Purpose:
Use classes to encapsulate the properties and behavior of objects
Tank.java
public class Tank { double speed; int bulletAmount; void speedUp(int s){ speed=s+speed; } void speedDown(int d){ if(speed-d>=0) speed=speed-d; else speed=0; } void setBulletAmount(int m){ bulletAmount=m; } int getBulletAmount(){ return bulletAmount; } double getSpeed(){ return speed; } void fire(){ if(bulletAmount>=1){ bulletAmount=bulletAmount-1; System.out.println("Play a shell"); } else{ System.out.println("No more shells, can't fire!"); } } }fight.java
public class Fight { public static void main(String[] args) { Tank tank1,tank2; tank1=new Tank(); tank2=new Tank(); tank1.setBulletAmount(10); tank2.setBulletAmount(10); System.out.println("The number of shells of tank1: "+tank1.getBulletAmount()); System.out.println("The number of shells of tank2: "+tank2.getBulletAmount()); tank1.speedUp(80); tank2.speedUp(80); System.out.println("The current speed of tank1: "+tank1.getSpeed()); System.out.println("The current speed of tank2: "+tank2.getSpeed()); tank1.speedDown(15); tank2.speedDown(30); System.out.println("The current speed of tank1: "+tank1.getSpeed()); System.out.println("The current speed of tank2: "+tank2.getSpeed()); System.out.println("tank1 fire: "); tank1.fire(); System.out.println("tank2 fire: "); tank2.fire(); tank2.fire(); System.out.println("The number of shells of tank1: "+tank1.getBulletAmount()); System.out.println("The number of shells of tank2: "+tank2.getBulletAmount()); } }
operation result: