子類覆蓋父類方法

如果父類方法是private,子類方法是public,這樣是覆蓋還是新定義的方法?

package com.subclassoverrideparent;

import static java.lang.System.*;

 

public class Person {

      private void fun(){   

            out.println("Person is fun");

      }

     

      public void print(){

            this.fun();

      }

}

 

package com.subclassoverrideparent;

import static java.lang.System.*;

 

public class Student extends Person {

     

      public void fun(){

            out.println("Student fun!");

      }

 

      public static void main(String[] args) {

            // TODO Auto-generated method stub

            new Student().print();

      }

 

}

輸出結果:Person is fun

說明沒有覆蓋父類的fun方法,子類重新定義了一個新的fun方法;

如果:Person=>protected void fun()

             Student=>public void fun()

則輸出結果:Student fun!

父類fun()方法被子類覆蓋了,結論:父類的private方法不允許被子類覆蓋

如果都是publicprotecteddefault,那當然是覆蓋了;

如果父類是public,則子類不允許訪問控制比public,即不能是protectedprivate等,系統會提示錯誤。

final 方法不能覆蓋,如果加static 修飾符,則調用時,調用的是父類的static方法.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章