java类作为成员变量

package test_class;

import com.sun.security.jgss.GSSUtil;

public class Hero {
    private String name;
    private int age;
    private Weapon w;
    public void attack(){
      System.out.println("年龄为"+age+"的"+name+"用"+w.getCode()+"攻击敌方");//为什么不用this ,因为该类方法没有参数与成员变量有歧义,
  }                                            //对象调用该方法时就传递的就是该对象的参数, 为什么name,age,没调用方法,因为他们是基本类型,Weapon是引用类型
    public Hero() {
    }
    public Hero(String name, int age, Weapon w) {
        this.name = name;
        this.age = age;
        this.w = w;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Weapon getW() {
        return w;
    }
    public void setW(Weapon w) {
        this.w = w;
    }
}

package test_class;
public class Weapon {
    private String code;
    public Weapon() {
    }
    public Weapon(String code) {
        this.code = code;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public void use_wep(){
        System.out.println("use"+code);
    }
    String name;
    int hurt;
}

package test_class;

public class demo_main {
    public static void main(String[] args) {
        Hero hero=new Hero();
        hero.setAge(19);
        hero.setName("ash");
        Weapon wp=new Weapon("duolan");
        System.out.println(hero.getAge());
        System.out.println(hero.getName());
        hero.setW(wp);//setW里面写的是Weapon类型  必须传入该类型的变量
        System.out.println(hero.getW().getCode());//getw()返回值是一个weapon对象,要得到属性,则要调用get,set方法
        hero.attack();
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值