编程语言
首页 > 编程语言> > java 类与对象典型例题

java 类与对象典型例题

作者:互联网

实验 1 Tank 类

实验目标:判断炮弹还有剩余

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("打出一发炮弹");
		}else{
			System.out.println("没有炮弹了,无法开火");
		}
	}
}

主类:

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("tank1 的炮弹数量: "+tank1.getBulletAmount());
    System.out.println("tank2 的炮弹数量: "+tank2.getBulletAmount());
    tank1.speedUp(80);
    tank2.speedUp(90);
    System.out.println("tank1 目前的速度: "+tank1.getSpeed());
    System.out.println("tank2 目前的速度: "+tank2.getSpeed());
    tank1.speedDown(15);
    tank2.speedDown(30);
    System.out.println("tank1 目前的速度: "+tank1.getSpeed());
    System.out.println("tank2 目前的速度: "+tank2.getSpeed());
    System.out.println("tank1 开火: ");
    tank1.fire();
    System.out.println("tank2 开火: ");
    tank2.fire();
    tank2.fire();
    System.out.println("tank1 的炮弹数量: "+tank1.getBulletAmount());
    System.out.println("tank2 的炮弹数量: "+tank2.getBulletAmount());
    }
    }

在这里插入图片描述

实验 2 家族的姓氏

主要考察static

public class FamilyPerson {
    static String surname;
    String name;
    public static void setSurName(String s){
        surname=s;
    }
    public void setName(String n){
        name=n;
    }
}
public class MainClass { 
    public static void main(String args[]) {
    FamilyPerson.surname="李";//用类名 FamilyPerson 访问 surname,并为 surname 赋值:"李"
    FamilyPerson father,sonOne,sonTwo;
    father = new FamilyPerson();
    sonOne = new FamilyPerson();
    sonTwo = new FamilyPerson();
    father.setName("向阳");//father 调用 setName(String s),并向 s 传递"向阳"
    sonOne.setName("抗日");
    sonTwo.setName("抗战"); 
    System.out.println("父亲:"+father.surname+father.name);
    System.out.println("大儿子:"+sonOne.surname+sonOne.name);
    System.out.println("二儿子:"+sonTwo.surname+sonTwo.name); 
    father.setSurName("张");// father 调用 setSurName(String s),并向 s 传递"张"
    System.out.println("父亲:"+father.surname+father.name);
    System.out.println("大儿子:"+sonOne.surname+sonOne.name);
    System.out.println("二儿子:"+sonTwo.surname+sonTwo.name); 
    }
   }

在这里插入图片描述

标签:典型,java,System,tank1,tank2,println,surname,例题,out
来源: https://blog.csdn.net/qq_42907061/article/details/118075098