zyf4005
zyf4005
2016-04-19 02:48
采纳率: 78.3%
浏览 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条回答 默认 最新

  • w172087242
    little_how 2016-04-19 03:47
    已采纳

    静态方法是类方法,表示只跟类的引用有关系Parent p2 = new Child()中,这个对象是父类引用,所以会调用父类的静态方法。

    一定要记住,静态方法跟对象是毫无关系的,因为静态方法内部能使用的变量也是静态的,静态的所有都是记录类的状态。

    希望能帮到你。

    点赞 评论
  • hnsywangxin
    hnsywangxin 2016-04-19 02:56

    静态方法不是属于某个对象的, 是所有对象共享的,父类和子类中不能有这样的方法同名的,一样参数的重写方法

    点赞 评论

相关推荐