频道直达 - 专题 - 新闻 - 技巧 - 组网 - 开发 - 安全 - web编程 - 图像 - 操作系统 - 数据库 - 教育 - 旅游 - 健康 - 时尚 - 驱动 - 软件 - 游戏 - 多媒体 - ERP - 讨论组

覆盖静态方法与非静态方法的区别

来源:J2ME开发网 作者:mingjava 出处:巧巧读书 2006-10-12 进入讨论组
  • 关 键 词:
  • 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的非静态方法,为什么呢?原因是静态方法是在编译的时候把静态方法和类的引用类型进行匹配,而不是在运行的时候和类引用进行匹配。因此我们得出结论:当我们在子类中创建的静态方法,它并不会覆盖父类中相同名字的静态方法。

查看 http://www.qqread.com/java/2006/10/c220867.html进入讨论组讨论。
收藏此文】【 】【打印】【关闭
相关图文阅读
频道图文推荐
健 康 咨 询
时 尚 咨 询
巧巧读书宗旨
相关专题
最新论坛文章
站内各频道最新更新文档
站内最新制作专题
热门关键字导读
Photoshop教 程照片处理 照片制作 PS快捷键 抠图
计 算 机 故 障XP系统修复
艺 术 与 设 计设计 流媒体 设计欣赏 边框
计 算 机 安 全ARP
站内频道文章精选
巧巧电脑频道编辑信箱  告诉我们您想看的专题或文章