当前位置: 代码迷 >> 综合 >> 深入理解java的this,super关键字
  详细解决方案

深入理解java的this,super关键字

热度:35   发布时间:2023-09-20 00:12:45.0

this指调用方法的对象;可以用在this()构造方法,return this;this只用在必要的时候;

Apple{Peel.peel(this)}此this指代apple对象省去创建apple对象代码;

package com.xxx.data.governance.utils;

public class Father {
    private int a=3;
    static{
        System.out.println("我是父类静态代码块");
    }
    Father(){
        System.out.println("我是父类构造方法");
    }
    public int test(){
        System.out.println("我是father的test方法");
        System.out.println(this);
        this.te();
        return 1;
    }
    public int te(){
        System.out.println("我是father的te方法");
        return 2;
    }
    public static void main(String[] args) {
        Father s = new Son();
        s.test();
        System.out.println(s.a);
    }
}

执行结果:

我是父类静态代码块
我是父类构造方法
我是son的test方法
我是father的test方法
com.pactera.data.governance.utils.Son@15db9742
我是son的te方法
3

package com.xxx.data.governance.utils;

public class Son extends Father {
    private int a=2;
    public int test(){
        System.out.println("我是son的test方法");
        //Father f =new Father();
        super.test();
        return 2;
    }
    public int te(){
        System.out.println("我是son的te方法");
        return 2;
    }
}