实例说明java中覆盖静态方法和非静态方法的不同
来源:互联网 发布:淘宝闲鱼网 ipad7.0 编辑:程序博客网 时间:2024/05/01 18:52
实例说明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的非静态方法,为什么呢?原因是静态方法是在编译的时候把静态方法和类的引用类型进行匹配,而不是在运行的时候和类引用进行匹配。因此我们得出结论:当我们在子类中创建的静态方法,它并不会覆盖父类中相同名字的静态方法。
- 实例说明java中覆盖静态方法和非静态方法的不同
- 实例说明java中覆盖静态方法和非静态方法的不同
- 实例说明java中覆盖静态方法和非静态方法的不同
- Java实例说明 静态方法和非静态方法的区别
- java中静态方法和非静态方法覆盖的区别
- java中覆盖静态方法和非静态方法的区别
- java中静态方法和非静态方法覆盖的区别
- java中静态方法和非静态方法覆盖的区别
- java中静态方法和非静态方法覆盖的区别
- Java中的实例方法、静态方法和数据域的覆盖和隐藏说明
- java中 静态方法和非静态方法的调用
- java中静态方法和非静态方法的存储
- Java中静态方法和非静态方法的区别
- java中静态方法和非静态方法的区别
- java静态方法与非静态方法 覆盖的区别
- JAVA中的静态方法和非静态方法的继承覆盖问题
- JAVA静态方法和非静态方法的区别和实例
- JAVA静态方法和非静态方法的区别和实例
- 手机配件信息列表
- 26周岁,年轻的心情渐行渐远!
- The 10 Things You Need to Know About Java SE 6 'Mustang'
- Defect Reporting (Section 2) --怎样使Defect Report更加Effective
- 每天进步一丁点~
- 实例说明java中覆盖静态方法和非静态方法的不同
- 基于C#的接口基础教程之一
- J2ME开发专题
- 疯狂元宝的代码分析
- 基本教程篇--第三节、第四节DateAxisSampleDemo.cs和TextAxisSampleDemo.cs介绍
- 2006技术图书评选
- 常用网站
- 基于C#的接口基础教程之二
- 美国网站兵败中国的10大思路性执行错误