静态方法与非静态方法的区别 使用static修饰的静态方法是属于整个类的类方法,它在内存中的代码段会随类的定义而被分配和装载;而非静态方法是属于具体对象的方法,当这个对象创建时,在对象的内存中会拥有此方法的专用代码段。在引用静态方法时,可以使用对象名加前缀,也可以使用类名加前缀 。
eg. classA 实例化了一个对象objectA,classA中定义了一个静态方法:run( ). 则可使用 classA.run( ) 或者objectA.run( )来执行。
非静态方法既可以访问静态数据成员又可以访问非静态数据成员,而静态方法只能访问静态数据成员;同样地非静态方法既可以访问静态方法又可以访问非静态方法,而静态方法只能访问静态数据方法。特别注意的是静态方法中的main方法,它作为程序运行的入口点,在每个程序中有且只能有一个。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class Person { public int age; public static double height; public static String Address (String x) { System.out.println("address:" +x); } public int Birthday (int x) { System.out.println("birthday is " +x+" month" ); } public static void main (String[] args) { age=24 ; height=173 ; Address("xi'an" ); Birthday(5 ); } }
编译时,就会出现无法从静态上下文中引用非静态变量age和非静态方法Birthday(int)的错误。
还有一点就是静态方法不能被覆盖,下面有一个形象的例子:
首先我们提供两个类,基类为Parent,派生类为Child。在Parent中我们提供两个方法,一个是静态方法staticMethod(),一个是非静态方法nonStaticMethod()。在Child类中我们覆盖着两个方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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()得到三个实例,并分别调用静态方法和非静态方法,我们来看程序的运行结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 2 3 4 5 6 7 8 Parent.static: parent's static method is called p1.static: parent' s static method is calledp2.static: parent's static method is called p1.nonStatic: Parent' s Non-Static Method is Calledp2.nonStatic: child's non-static method is called Child.static: child' s static method is calledc.static: child's static method is called c.nonStatic: child' s non-static method is called
值得注重的是p2实际上是一个Child的类型的引用,然而在调用静态方法的时候,它执行的却是父类的静态方法,而不是Child的静态方法,而调用 p2的非静态方法的时候执行的是Child的非静态方法,为什么呢?原因是静态方法是在编译的时候把静态方法和类的引用类型进行匹配,而不是在运行的时候 和类引用进行匹配。因此我们得出结论:当我们在子类中创建的静态方法,它并不会覆盖父类中相同名字的静态方法。
原文地址