java中this调用方法如何使用
时间: 2023-06-02 07:03:25 浏览: 54
当你在一个类中定义一个方法时,可以在方法内部使用关键字 "this" 来引用当前对象。如果方法内部同时存在名称相同的局部变量和对象成员变量时,使用 "this" 可以明确地指示使用对象成员变量,而不是局部变量。比如:
public class Fruit {
private String name;
public Fruit(String name) {
this.name = name;
}
public void printName() {
System.out.println("Fruit name is: " + this.name);
}
}
在这个例子中,构造方法中传入了一个名字参数并将其赋值给对象的成员变量name,而 printName 方法使用关键字 "this" 来访问对象的成员变量name,从而打印出水果的名字。
相关问题
java中this调用构造方法
在Java中,可以使用this关键字来调用同一个类中的其他构造方法。这种方式被称为构造方法的重载。使用this调用构造方法的语法格式如下:
```
public class MyClass {
private String name;
private int age;
// 构造方法1
public MyClass() {
this("Tom", 20); // 调用构造方法2
}
// 构造方法2
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
}
```
在上面的例子中,构造方法1调用了构造方法2,使用了this关键字来指定调用的是同一个类中的另一个构造方法。这样就可以避免代码重复,提高了代码的可维护性。需要注意的是,this调用构造方法必须放在构造方法的第一行,否则会编译出错。
java中使用this关键字调用构造方法
在Java中,可以使用this关键字调用同一个类中的构造方法。这种技术被称为构造方法重载或构造方法重复。在调用构造方法时,可以使用this关键字传递参数并调用另一个构造方法。
以下是使用this关键字调用构造方法的示例:
```
public class Person {
private String name;
private int age;
public Person() {
this("John Doe", 30);
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
```
在上面的示例中,第一个构造方法调用了另一个构造方法,使用了this关键字并传递了默认值。这样,第二个构造方法就会被调用并设置实例的属性值。