this()方法与this属性

本文详细介绍了Java中的this关键字使用方法,包括如何通过this调用当前类的属性和构造方法。重点讲解了在一个构造方法中调用另一个构造方法的技巧。
“this属性” 这说法不知道对不对,这里也不用理它

我们在一个java文件中,一般只用到了这个this.***来取得一个类属性;而对this()方法用的却很少用到,因为这个方法只能用在构造函数中。

下面是个例子:

public class TestThis {
    
    
int x;
    
int y;
    
int z;
    
    
public TestThis(int x, int y) {
        
this.x = x;
        
this.y = y;
    }


    
public TestThis(int x, int y, int z) {
        
this(x,y);
        
this.z = z;
    }


}

Java 中,`this.属性`、`this.方法` `this()` 有着不同的用途和含义。 ### `this.属性` 和 `this.方法` `this` 关键字表示对当前对象的引用,`this.属性` 和 `this.方法` 用于明确地引用当前对象的属性方法。当在类的方法中存在成员变量同名的局部变量时,使用 `this.属性` 可以区分成员变量和局部变量。同样,`this.方法` 可以调用当前对象的其他方法。 示例代码如下: ```java class Person { private String name; public Person(String name) { // 使用 this.属性 来区分局部变量和成员变量 this.name = name; } public void introduce() { // 使用 this.方法 调用当前对象的其他方法 this.sayHello(); System.out.println("My name is " + this.name); } public void sayHello() { System.out.println("Hello!"); } } public class Main { public static void main(String[] args) { Person person = new Person("Alice"); person.introduce(); } } ``` 在上述代码中,`this.name` 明确地引用了当前对象的 `name` 成员变量,`this.sayHello()` 调用了当前对象的 `sayHello` 方法。 ### `this()` `this()` 是在构造方法中调用同一个类的其他构造方法的方式,也称为构造方法的重载调用。使用 `this()` 可以避免代码重复,提高代码的复用性。需要注意的是,`this()` 必须是构造方法中的第一条语句。 示例代码如下: ```java class Rectangle { private int width; private int height; public Rectangle() { // 调用另一个构造方法 this(0, 0); } public Rectangle(int width, int height) { this.width = width; this.height = height; } public int getArea() { return this.width * this.height; } } public class Main { public static void main(String[] args) { Rectangle rectangle = new Rectangle(); System.out.println("Area: " + rectangle.getArea()); } } ``` 在上述代码中,无参构造方法 `Rectangle()` 调用了带两个参数的构造方法 `Rectangle(int width, int height)`,使用 `this(0, 0)` 实现了构造方法的重载调用。 ### 区别总结 - **用途不同**:`this.属性` 和 `this.方法` 用于引用当前对象的属性方法,而 `this()` 用于在构造方法中调用同一个类的其他构造方法。 - **使用位置不同**:`this.属性` 和 `this.方法` 可以在类的任何实例方法中使用,而 `this()` 只能在构造方法中使用,并且必须是构造方法中的第一条语句。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值