Java教程

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 类与对象典型例题的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!