this&super
this和super在java中是比较重要而且有点可比性的两个关键字。现在将this和super关键字的相关用法进行总结
this
this关键字使用在一个成员函数的内部,指向当前对象,当前对象指的是调用当前正在执行方法的那个对象。
Java关键字this只能用于方法方法体内。当一个对象创建后,Java虚拟机就会给这个对象分配一个引用自身的指针,这个指针的名字就是this。this只能在类的非静态方法中使用,静态方法或静态方法块中不能使用this关键字。
this用法
在类的构造函数中,可以通过this调用另一个构造函数,当使用this(…)语法时从一个构造方法中重用另一个构造方法的代码时,注意这条语句必须是这个构造函数的第一条语句。
package thisTest; public class Student { private String name; private String sale; private int age; //构造函数1 public Student() { } //构造函数2 public Student(String s , String sale){ this(); this.sale = sale; } //构造函数3 public Student(String s , String sale , int age){ this(s ,sale); this.age = age; } }
函数参数或者函数中的局部变量和成员变量同名的情况下,成员变量被屏蔽,此时要访问成员变量则需要使用“this.成员变量名”的方式来引用成员变量。
package thisTest; public class Student { private String name; private String sale; private String address; private int age; public void Student(String name, String sale, String address, int age){ this.name = name; this.sale = sale; this.address = address; this.age = age; } }
- 在函数中,需要引用函数所属类的当前对象时候,直接用this。
super
super关键字是直接指向超类的构造函数,用来引用超类中的变量和方法。
super用法
子类通过super调用父类的构造函数。当使用super()语法时,子类构造方法中调用父类构造函数,必须把super放在函数的首行。
package superTest; public class Base { public Base() { System.out.println("Base"); } } ------------------------------------------- package superTest; public class Checket extends Base { public Checket() { super(); System.out.println("Checket"); } } --------------------------------------------- package superTest; public class MainTest { public static void main(String[] args) { Checket c = new Checket(); } } 输出结果为:Base Checket
PS:如果想要super继承父类构造函数的方法,但是没有放在第一行,那么在super之前的语句肯定是为了满足自己想要完成某些行为的语句,但是又用了super继承父类的构造方法。那么以前所做的修改就都回到了以前,就是说又成了父类的构造函数。
子类中的成员变量或方法与父类的成员变量或方法同名。因为子类中的优先级高于父类。所以子类中的同名成员变量或方法名就隐藏了父类的成员变量或方法。如果我们想使用父类中的成员变量和方法,就需要用到super。
package superTest1; public class Country { protected String name; public void value() { name = "China"; } } --------------------------------------- package superTest1; public class City extends Country{ private String name; public void value(){ name = "GuangZhou"; super.value(); System.out.println(name); System.out.println(super.name); } } -------------------------------------- package superTest1; public class MainTest { public static void main(String[] args) { City city = new City(); city.value(); } } 输出结果:GuangZhou China
子类使用父类的构造函数应当使用super(参数列表)的形式。