java中得this与super

来源:百度知道 编辑:UC知道 时间:2024/05/23 15:41:35
class Parent
{
void printMe()
{
System.out.println("parent");
}
}

class Child extends Parent
{
void printMe()
{
System.out.println("child");
}
void printAll()
{
super.printMe();
this.printMe();
printMe();
}
}

public class Test_this
{
public static void main(String[] args)
{
Child myC=new Child();
myC.printAll();
}
}

输出结果:parent parent child

或者 parent child child
请问哪个正确。。为什么。。谢谢。。

parent child child

super指的是调用的父类的方法
但是child里面把父类的printMe重写了 所以 this.方法名和直接方法名调用的都是子类的 也就是本身

在没有相同变量或方法的情况下
this.调用

直接调用
没有区别的

parent child child
super.printMe(); 这调用的是父类的;
this.printMe(); 这调用的是自己的
printMe(); 还是调用自己的