本文共 2159 字,大约阅读时间需要 7 分钟。
构造方法中的this关键字
构造方法是一个类的对象在通过new关键字创建时自动调用的特殊方法。在Java中,构造方法有其独特的调用方式,与普通方法不同。然而,如果一个类有多个构造方法,调用其他构造方法时需要使用this关键字。以下是使用this关键字在构造方法中的注意事项。
第一,this关键字只能在构造方法中使用,不能在普通方法中使用。第二,在构造方法中使用this调用其他构造方法时,不能进行递归调用,即不能直接或间接地调用自己或同一个构造方法。第三,通过this调用其他构造方法必须放在构造方法的第一行执行,否则会导致语法错误。同样,super用于调用父类构造方法也必须放在构造方法的第一行,因此在一个构造方法中不能同时使用this和super。
在非构造方法中,this关键字用于访问类中的成员变量和成员方法。具体来说:
需要注意的是,通过this访问的成员变量和方法可以访问本类中所有的成员,包括private成员。然而,通过this访问static成员可能会产生警告,因为static成员可以通过类名直接访问。
在继承关系中,this关键字的含义可能会因上下文而有所不同:
以下是一个示例:
public class ClassTest {public static void main(String[] args) {Child child = new Child();child.show();}}
class Parent {public String str;Parent() {this(1);}Parent(int a) {this.str = "Parent";this.show();}public void show() {System.out.println(this.str);}}
class Child extends Parent {public String str;Child() {}Child(int a) {str = "Child";}public void show() {System.out.println(str);super.show();}}
在这个例子中,当使用new Child()时,Child类的无参数构造方法会调用Parent类的无参数构造方法。Parent类的无参数构造方法会调用Parent(int)构造方法,进而赋值Parent类的str字段为"Parent"。接着,Parent(int)构造方法会调用show()方法,打印"Parent"。
当调用child.show()时,Child类的show()方法会先打印自己的str字段(null),然后调用super.show(),打印Parent类的str字段("Parent")。因此,输出为null, Parent。
如果将new Child(1)改为new Child(),则结果会有所不同。Child(int)构造方法会赋值自己的str字段为"Child",然后调用super.show(),打印自己的str字段("Child"),再打印Parent类的str字段("Parent")。因此,输出为null, Child, Child, Parent。
super和this的区别
super和this在Java中是不同的概念。在代码中,super和this表示不同的对象引用。super表示父类的引用,而this表示当前类对象的引用。例如:
public class ClassConstructorTest {public static void main(String[] args) {Child child = new Child();child.show();}}
class Parent {private Parent mSelf;Parent() {mSelf = this;}public void show() {System.out.println(this.getClass().getName());System.out.println(super.getClass().getName());System.out.println(mSelf.getClass().getName());}}
class Child extends Parent {public void show() {System.out.println(this.getClass().getName());System.out.println(super.getClass().getName());super.show();}}
转载地址:http://qhhq.baihongyu.com/