java构造函数的应用场合,java this 使用场景 | 学步园

本文介绍了Java中`this`关键字的作用,特别是在成员变量与局部变量冲突时如何通过`this`来指代对象的成员变量。同时,展示了如何在不同构造函数之间使用`this`调用来避免代码重复,并确保对象初始化的正确性。
摘要由CSDN通过智能技术生成

翻译自http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

场景1. 成员变量被某个方法(一般是set方法或者构造函数)中的local变量屏蔽

例如:

public class Point {

public int x = 0;

public int y = 0;

//constructor

public Point(int a, int b) {

x = a;

y = b;

}

}

构造函数里的local变量如果也使用x,y呢

public class Point {

public int x = 0;

public int y = 0;

//constructor

public Point(int x, int y) {

this.x = x;

this.y = y;

}

}

加上this就指定是本对象的变量而非local变量

场景2. 调用另外一个构造函数

例如:

public class Rectangle {

private int x, y;

private int width, height;

public Rectangle() {

this(0, 0, 0, 0);

}

public Rectangle(int width, int height) {

this(0, 0, width, height);

}

public Rectangle(int x, int y, int width, int height) {

this.x = x;

this.y = y;

this.width = width;

this.height = height;

}

...

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值