JavaSE之super和this的区别

面试题: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();
    }

}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值