Java中什么情况下不能省略 this 关键字?

1、this 可以在实例方法中,不能使用在静态方法中。

2、this 关键字大部分情况下可以省略,那什么时候不能省略呢?

        思考一下以下代码

public class ThisTest{
    public class void main(String[] args) {
        Student s = new Student();
        s.setNum(111);
        s.setName("张三");
        System.out.println("学号" + s.getNum());
        System.out.println("姓名" + s.getName( ) );

        Student s = new Student(2222, "李四");
        System.out.println("学号" + s2.getNum());
        System.out.println("姓名" + s2.getName( ) );
    }
}

// 分析一下:一下代码哪里写的不好
// 学生类
class Student{
    // 学生号
    private int num;
    
    // 姓名
    private String name;

    // 无参构造方法
    public Student() {

    }

    // 有参构造方法
    public Student( int i, String s ) {
        num = i;
        name = s;
    }

    // setter and getter 方法
    public void setNum(int i) {
        num = i;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值