最近对JAVA的运行感到兴趣了
public class TestStaticMethodExtends {
public static void main(String[] args) {
A www = new B();
A c=new B();
www.p();
A.p();
c.p();
}
}
class A {
public static void p() {
System.out.println("基类");
}
}
class B extends A {
public static void p() {
System.out.println("子类");
}
}
}
这段代码javap -c后是这样的
C:\Users\Administrator>javap -c Desktop\TestStaticMethodExtends.class
Compiled from "TestStaticMethodExtends.java"
public class TestStaticMethodExtends {
public TestStaticMethodExtends();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return public static void main(java.lang.String[]);
Code:
0: new #2 // class B
3: dup
4: invokespecial #3 // Method B."<init>":()V
7: astore_1
8: new #2 // class B
11: dup
12: invokespecial #3 // Method B."<init>":()V
15: astore_2
16: aload_1
17: pop
18: invokestatic #4 // Method A.p:()V
21: invokestatic #4 // Method A.p:()V
24: aload_2
25: pop
26: invokestatic #4 // Method A.p:()V
29: return
}
如果我没有理解错的话,JAVA运行静态方法的时候完全是不看是哪个对象在调用,而是看哪个类的。
但是为什么JAVA不限制对象.静态方法这种调用方法呢?
另外,求推荐JAVA运行机制的书
public class TestStaticMethodExtends {
public static void main(String[] args) {
A www = new B();
A c=new B();
www.p();
A.p();
c.p();
}
}
class A {
public static void p() {
System.out.println("基类");
}
}
class B extends A {
public static void p() {
System.out.println("子类");
}
}
}
这段代码javap -c后是这样的
C:\Users\Administrator>javap -c Desktop\TestStaticMethodExtends.class
Compiled from "TestStaticMethodExtends.java"
public class TestStaticMethodExtends {
public TestStaticMethodExtends();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":
()V
4: return public static void main(java.lang.String[]);
Code:
0: new #2 // class B
3: dup
4: invokespecial #3 // Method B."<init>":()V
7: astore_1
8: new #2 // class B
11: dup
12: invokespecial #3 // Method B."<init>":()V
15: astore_2
16: aload_1
17: pop
18: invokestatic #4 // Method A.p:()V
21: invokestatic #4 // Method A.p:()V
24: aload_2
25: pop
26: invokestatic #4 // Method A.p:()V
29: return
}
如果我没有理解错的话,JAVA运行静态方法的时候完全是不看是哪个对象在调用,而是看哪个类的。
但是为什么JAVA不限制对象.静态方法这种调用方法呢?
另外,求推荐JAVA运行机制的书
这个代码也许更有意思:
A a = null;
a.p();