java重的this,重学java-9.初步认识this关键字

重学java-9.初步认识this关键字

初步认识this关键字

调用本类属性

举个例子:

class Emp {

private int id;

private String name;

private double sal;

private String dept;

//最常用的就是用this代表本类属性,比如this.id=id就方法中的参数id给类中的参数id赋值

public Emp(int id, String name, double sal, String dept) {

this.id = id;

this.name = name;

this.sal = sal;

this.dept = dept;

}

}

调用本类普通方法

举个例子:

class Emp {

private int id;

private String name;

private double sal;

private String dept;

public Emp(int id, String name, double sal, String dept) {

this.id = id;

this.name = name;

this.sal = sal;

this.dept = dept;

this.getInfo();//调用本类方法

}

public String getInfo() {

return "id: "+ id +" name: "+ name + " sal: " + sal + " dept: " + dept;

}

}

调用构造方法

举个例子,把有4个参数的所有构造方法写出来。

class Emp {

private int id;

private String name;

private double sal;

private String dept;

public Emp() {

this(0,"nobody",0.0,"none");

};

public Emp(int id) {

this(id,"nobody",0.0,"none");

}

public Emp(int id, String name) {

this(id,name,0.0,"none");

}

public Emp(int id, String name, double sal) {

this(id,name,sal,"none");

}

//前三个构造方法都调用第四个构造方法,节省了许多的重复代码

public Emp(int id, String name, double sal, String dept) {

this.id = id;

this.name = name;

this.sal = sal;

this.dept = dept;

this.getInfo();

}

public String getInfo() {

return "id: "+ id +" name: "+ name + " sal: " + sal + " dept: " + dept;

}

}

注意: 用this调用本类方法的时候,一定要注意保留出口,否则会无限递归。

表示当前对象

举个例子:

class Emp {

private int id;

private String name;

private double sal;

private String dept;

public Emp getInfo() {

return this;//返回的是对象

}

}

测试代码:

public static void main(String[] args) {

Emp empa = new Emp();

Emp empb = new Emp();

System.out.println(empa + " " + empa.getInfo());

System.out.println(empb + " " + empb.getInfo());

}

输出结果:

6caaff6aa35f87ae6de401a303149d79.png

可以看出,this所指的内存与调用该方法的对象实体保持一致。

标签:重学,java,name,sal,private,dept,关键字,id,String

来源: https://blog.csdn.net/euzmin/article/details/89280118

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值