Netjava Lesson2 类和对象

2013.07.06

 

上课内容:类和对象

 

定义:
对象:生活中的某一个物品或者某一个事物,这里要尤其注重是某一个,统称的物品不算对象。
 如篮球就不算对象,熊哥算对象。
类: 一些拥有相同或相似特征的对象的集合,在程序中,类是一个固定的模版,这些对象都含有一些相同的特征,但属性并不一定相同。
 java中类包括属性和方法。
 如学生有姓名、性别、学号、成绩等属性,有学习、玩游戏、吃饭、睡觉等方法。
 
下面是在程序中类的实现方法:
设置属性:
private 数据类型  属性名;
设置方法:
public 返回值类型  方法名;

 

我们以学生为例:

//建立一个学生类
public class Student(){
//设置属性
	private string name;
	private char sex;
	private int num;
	private int score;
//创建一个方法,能够修改属性
	public void setName(string name){
		this.name=name;
	}
//创建一个方法能够获取属性的值
	public string getname(){
		return name;
	}
}

 

调用对象和调用方法:
类名  对象名=new 类名();
对象名.方法名(实参);

 

以上述的学生为例:

//创建对象stu
Student stu=new Student();
//调用stu的方法设置姓名
stu.setName("Teemo");
//将stu的姓名返回给字符串st
string st=stu.getName();

 

练习:
我们以LOL中的提莫队长和纳什男爵的回合制战斗为背景,直到有一方血量为0为止,输出战斗过程,并在最后输出谁胜利了!
提莫和纳什男爵拥有相同的属性:血量,攻击力,防御力。其中防御力代表的是每次减免百分之多少的伤害。
定义的方法BeAttacked作为一回合攻击血量的变化值。
附程序如下:

package cn.tth.pratice0706;

public class Scence {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			Teemo te = new Teemo();
			Nashor na = new Nashor();
			te.setAtk(200);te.setDef(50);te.setHp(1500);
			na.setAtk(100);na.setDef(25);na.setHp(5000);
			while(te.getHp()>0&&na.getHp()>=0){
				te.BeAttacked(na);
				na.BeAttacked(te);
				int nahp=(int)na.getHp();
				int tehp=(int)te.getHp();
				System.out.println("Nashor's hp="+nahp+"    Teemo's hp="+tehp);
			}
			if(te.getHp()<=0){
				System.out.println("Nashor win!");
			}else{
				System.out.println("Teemo win!");
			}			
	}
}

package cn.tth.pratice0706;

public class Teemo {
	private int atk;	
	private int def;
	private double hp;
	public int getAtk() {
		return atk;
	}
	public void setAtk(int atk) {
		this.atk = atk;
	}
	public int getDef() {
		return def;
	}
	public void setDef(int def) {
		this.def = def;
	}
	public double getHp() {
		return hp;
	}
	public void setHp(int hp) {
		this.hp = hp;
	}
	public void BeAttacked(Nashor na){
		hp=hp-na.getAtk()*(1-def/100.0);
	}	
}

package cn.tth.pratice0706;

public class Nashor {
	private int atk;	
	private int def;
	private double hp;
	public int getAtk() {
		return atk;
	}
	public void setAtk(int atk) {
		this.atk = atk;
	}
	public int getDef() {
		return def;
	}
	public void setDef(int def) {
		this.def = def;
	}
	public double getHp() {
		return hp;
	}
	public void setHp(int hp) {
		this.hp = hp;
	}
	public void BeAttacked(Teemo te){
		hp=hp-te.getAtk()*(1-def/100.0);
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值