第一題:
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 個錯誤
靜態方法是類方法,表示只跟類的引用有關系Parent p2 = new Child()中,這個對象是父類引用,所以會調用父類的靜態方法。
一定要記住,靜態方法跟對象是毫無關系的,因為靜態方法內部能使用的變量也是靜態的,靜態的所有都是記錄類的狀態。
希望能幫到你。