面试题:super和this的区别
1.this关键字
this表示当前对象:
this.属性 区别成员变量和局部变量
this.() 调用本类的某个方法
this() 调用本类的构造方法,必须写在第一行
2. super关键字
super表示父类对象:
super.属性 表示父类对象中的成员变量
super.() 表示父类的某个方法
super() 调用父类的构造方法,必须写在第一行
编译报错:
当子类继承父类需要先初始化继承过来的父类的成员,此时需要通过super来完成。很明显在子类的构造方法当中,并没有通过super调用父类的构造方法。
3.注意
1.super和this只能在非静态方法中引用
2.super和this在调用构造方法时,必须写在第一行,且不能同时出现
4.代码解析
import java.util.Scanner; public class Tt { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNextInt()) { int x = scanner.nextInt(); int y = scanner.nextInt(); int z = scanner.nextInt(); Sub sub = new Sub(x, y, z); System.out.println(sub.calculate()); } } } class Base2 { private int x; private int y; public Base2(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } class Sub extends Base2 { private int z; public Sub(int x, int y, int z) { super(x,y); this.z = z; } public int getZ() { return z; } public int calculate() { return super.getX() * super.getY() * this.getZ(); } }
运行结果: