zyf4005
2016-04-19 02:48
采纳率: 100%
浏览 1.8k
已采纳

java中子类的静态方法能否覆盖父类的静态方法?请大神们帮忙分析下!

第一题:
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");     
    }      

}

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

}

}

问题1.
//Parent.static:parent's static method is called;
//p1.static:parent's static method is called;
//p2.static:parent's static method is called 结果为啥不是p2.static:child'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;

第二题:

class ExtendDemo2
{
public static void main(String[] args)
{
Zi z=new Zi();
z.show();
}
}

class Fu
{
static void show()
{
System.out.println("123");
}
}

class Zi extends Fu
{
void show()
{
System.out.println("234");
}
}

运行结果为:
D:\延飞>javac ExtendDemo2.java
ExtendDemo2.java:21: 错误: Zi中的show()无法覆盖Fu中的show()
static void show()
^
覆盖的方法为 static
1 个错误

问题2.为啥会有以上错误提示?
问题3.假如我把子类的show()改为void show(); 父类改为static void show();
结果为啥还是:D:\延飞>javac ExtendDemo2.java
ExtendDemo2.java:20: 错误: Zi中的show()无法覆盖Fu中的show()
void show()
^
被覆盖的方法为static
1 个错误

2条回答 默认 最新

相关推荐 更多相似问题