JAVA --类与对象(六)传参
基本类型的传参
方法内无法修改方法外的基本类型变量。
public class hero {
int hp;
float armor;
float movespeed;
String name;
public void huixue(int xp) {
hp+=xp;
xp = 0;
}
public hero(String name,int hp) {
this.name = name;
this.hp = hp;
}
public static void main(String args[]) {
hero a = new hero("二狗",50);
System.out.println("姓名:" + a.name);
System.out.println("当前血量:" + a.hp);
a.huixue(50);
System.out.println("经过血瓶的治疗后,血量为:" + a.hp);
}
}
引用
基本类型的赋值操作:
int i = 0;
类类型的指向操作:
(此时的a,不叫做变量,叫引用)
hero a = new hero();
类类型传参
public class hero {
int hp;
float armor;
float movespeed;
String name;
public void huixue(int xp) {
hp+=xp;
xp = 0;
}
public hero(String name,int hp) {
this.name = name;
this.hp = hp;
}
public void attack(hero a,int damage) { //这里是类类型传参
a.hp -=damage;
}
public static void main(String args[]) {
hero a = new hero("二狗",50);
hero b = new hero("提莫",50);
System.out.println("姓名:" + a.name + "当前血量:" + a.hp);
System.out.println("姓名:" + b.name + "当前血量:" + b.hp);
a.huixue(50);
System.out.println("经过血瓶的治疗后," + a.name + "血量为:" + a.hp);
System.out.println("二狗对提莫发起攻击,提莫血量为:" + b.hp);
a.attack(b, 20); //这里是普通方法传参
}
}
综合练习:在方法中,使参数引用指向一个新的对象
外面的引用是指向原来的对象?还是新的对象?
public class heros {
int hp;
String name;
float armor;
int movespeed;
public heros() {
}
public heros(String name,int hp) {
this.name = name;
this.hp = hp;
}
public void fuhuo(heros h) {
h = new heros("提莫",383);
}
public static void main(String args[]) {
heros a =new heros("德玛",383);
a.hp-=400;
a.fuhuo(a);
System.out.println("提莫的血量为:" + a.hp);
}
}
答案是:-17