浅析Java中super以及this关键字用法

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);

    }
}

输出如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值