java中this关键字

在java中,this关键字在实例化过程中,new的是谁this就是谁,但是对于成员变量来说没有多态,因此是this.成员变量,在哪就是用的哪个成员变量,

主类

package ThisTest;

import java.lang.reflect.InvocationTargetException;

public class Test {

    public  static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException {
        Fu f = new Zi();

        System.out.println(f.name);
        System.out.println(f.fun());

        f.show();
    }




}
package ThisTest;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Fu {

    public String name = "baba";

    public void show() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, InstantiationException {
        System.out.println("show:" + this.name);
        System.out.println(this.fun());
        System.out.println("*********************");

        Class clazz = this.getClass();
        System.out.println(""+clazz.getName());
        Object o = clazz.newInstance();

        Method md = clazz.getMethod("fun", null);
        Object invoke = md.invoke(o, null);
        System.out.println(invoke);
        System.out.println("--------------------------");
    }

    public String fun() {
        System.out.println("fun:" + this.name);
        System.out.println("--------------------------");
        return "我是父类调用";
    }
}
package ThisTest;

public class Zi extends Fu {
    public String name = "erzi";

    @Override
    public String fun() {
        System.out.println(this.name);
        System.out.println("--------------------------");
        return "我是子类fun()";
    }
}

输出结果 

baba
erzi
--------------------------
我是子类fun()
show:baba
erzi
--------------------------
我是子类fun()
*********************
ThisTest.Zi
erzi
--------------------------
我是子类fun()
--------------------------

 

你可能感兴趣的:(java中this关键字)