this关键字
this 关键字用来表示当前对象本身,或当前类的一个实例,通过 this 可以调用本对象的所有方法和属性。
1 public class Demo{ 2 public int x = 10; 3 public int y = 15; 4 public void sum(){ 5 // 通过 this 点取成员变量 6 int z = this.x + this.y; 7 System.out.println("x + y = " + z); 8 } 9 10 public static void main(String[] args) { 11 Demo obj = new Demo(); 12 obj.sum(); 13 } 14 } 15 运行结果: 16 x + y = 25
super关键字
super 关键字与 this类似,this 用来表示当前类的实例,super 用来表示父类。
super 关键字的功能:
- 调用父类中声明为 private 的变量。
- 点取已经覆盖了的方法。
- 作为方法名表示父类构造方法。
调用隐藏变量和被覆盖的父类方法
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 dog adog =new dog(); 6 adog.move(); 7 } 8 } 9 10 class animals{ 11 private String desc="animal is human good friend"; 12 public String getDesc(){return desc;}//必须要声明一个 getter 方法 13 public void move(){ 14 System.out.println("animal can move"); 15 } 16 } 17 class dog extends animals{ 18 public void move(){ 19 super.move();// 调用父类的方法 20 System.out.println("dogs can move "+super.getDesc());// 通过 getter 方法调用父类隐藏变量 21 } 22 }