執行個體說明java中覆蓋靜態方法和非靜態方法的不同

來源:互聯網
上載者:User

      本文將通過執行個體的示範說明在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的非靜態方法,為什麼呢?原因是靜態方法是在編譯的時候把靜態方法和類的參考型別進行匹配,而不是在啟動並執行時候和類引用進行匹配。因此我們得出結論:當我們在子類中建立的靜態方法,它並不會覆蓋父類中相同名字的靜態方法。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.