2021-03-15(双体系封装 / 构造方法)

双体系封装 / 构造方法

一、类成员的权限

在这里插入图片描述


二、set / get (Alt + insert)

public class StxStuOne {
    private String name;
    private String id;
    private int age;
    private int gender;

    // 返回给main函数
    public String getName() {
        return "My name is:" + name;
    }
    // 从main函数中得到参数
    public void setName(String name) {
        this.name = name;
    }
}
-------------------------------------------------------------------------
public static void main(String[] args) {
    StxStuOne stuOne = new StxStuOne();
    stuOne.setName("dyl");
    System.out.println(stuOne.getName());
}

三、构造方法

(一)要求

1. 方法名和类名相同

2.无返回值


(二) this() 作为构造方法使用

1、作用

当要求发生改变时,不需要改每个方法中需要改变的参数,只需要在最开始定义那个参数的方法里,改变那个参数就行。

2、规范

1.this指代构造方法,必须位于方法第一行

2.必须要上面已经定义过


(三)代码

public class StxStuOne {
    private String name;
    private String id;
    private int age;
    private int gender;

    // 默认无参构造方法
    public StxStuOne() {
    }

    public StxStuOne(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public StxStuOne(String id, String name, int age, int gender) {
//      this.id = id;
//      this.name = name;
//   this指代构造方法,必须位于方法的第一行
        this(id, name);    //相当于上面被注释的两行代码,但是需要上面已经定义过才能使用
        this.setAge(age);
        this.setGender(gender);
    }
-------------------------------------------------------------------------
public static void main(String[] args) {
    StxStuOne stu1 = new StxStuOne("004", "hzr");
    StxStuOne stu2 = new StxStuOne("003", "ly", 20, 2);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值