实例说明java中覆盖静态方法和非静态方法的不同
本文将通过实例的演示说明在java中覆盖静态方法和非静态方法的不同之处。并在文章最后给出具体的解释。
首先我们提供两个类,基类为Parent,派生类为Child。在Parent中我们提供两个方法,一个是静态方法staticMethod(),一个是非静态方法nonStaticMethod()。在Child类中我们覆盖着两个方法。
class Parent
{
public void nonStaticMethod()
{
System.out.println("Parent's Non-Static Method is Called");
}
public static void staticMethod()
{
System.out.println("parent's static method is called");
}
}
class Child extends Parent
{
public void nonStaticMethod()
{
System.out.println("child's non-static method is called");
}
public static void staticMethod()
{
System.out.println("child's static method is called");
}
}
在Test类中我们分别使用Parent p1 = new Parent(),Parent p2 = new Child(),Child c = new Child()得到三个实例,并分别调用静态方法和非静态方法,我们来看程序的运行结果
public class Test
{
public static void main(String args[])
{
Parent p1 = new Parent();
Parent p2 = new Child();
Child c = new Child();
System.out.print("Parent.static: "); Parent.staticMethod();
System.out.print("p1.static: "); p1.staticMethod();
System.out.print("p2.static: "); p2.staticMethod();
System.out.print("p1.nonStatic: "); p1.nonStaticMethod();
System.out.print("p2.nonStatic: "); p2.nonStaticMethod();
System.out.print("Child.static: "); Child.staticMethod();
System.out.print("c.static: "); c.staticMethod();
System.out.print("c.nonStatic: "); c.nonStaticMethod();
}
}
程序的运行结果为:
Parent.static: parent's static method is called
p1.static: parent's static method is called
p2.static: parent's static method is called
p1.nonStatic: Parent's Non-Static Method is Called
p2.nonStatic: child's non-static method is called
Child.static: child's static method is called
c.static: child's static method is called
c.nonStatic: child's non-static method is called
值得注意的是p2实际上是一个Child的类型的引用,然而在调用静态方法的时候,它执行的却是父类的静态方法,而不是Child的静态方法,而调用 p2的非静态方法的时候执行的是Child的非静态方法,为什么呢?原因是静态方法是在编译的时候把静态方法和类的引用类型进行匹配,而不是在运行的时候和类引用进行匹配。因此我们得出结论:当我们在子类中创建的静态方法,它并不会覆盖父类中相同名字的静态方法。