super以及this关键字的区别:
当父类被继承,同时子类中定义了与父类同名变量时,使用super来引用父类的成分,而用this来引用当前对象。
package com.kaopuyun.study.test;
/**
* @author create by Lin Xin
* @date 2018/12/19 17:42
*/
/**
* 使用super来引用父类的成分,用this来引用当前对象
* 子类继承父类,并且子类中定义了与父类相同名称的变量,则用super关键字,表示为父类变量
*/
public class TestSuper {
public static void main(String[] args) {
SuperChildren superChildren = new SuperChildren();
superChildren.SuperFather();
}
}
class SuperFather {
public int i;
public int j;
public void SuperFather() {
i = 111;
j = 222;
System.out.println("父类:" + i);
System.out.println("父类:" + j);
}
}
class SuperChildren extends SuperFather {
public int i;
public int j;
/**
* 在子类SuperChildren里面重写了从父类继承下来的SuperFather()方法里面的实现,即重写了SuperFather()方法的方法体。
*/
public void SuperFather() {
//使用super作为父类对象的引用对象来调用父类对象里面的SuperFather()方法
super.SuperFather();
i = 1333;
j = 1444;
System.out.println("子类:" + i);
System.out.println("子类:" + j);
/**
* super表示父类同名变量
*/
System.out.println("super:" + super.i);
System.out.println("super:" + super.j);
/**
* this表示此类中变量
*/
System.out.println("this:" + this.i);
System.out.println("this:" + this.j);
}
}
输出如下: