Java類的設計----方法的重寫、覆蓋

來源:互聯網
上載者:User

標籤:system   int   private   span   main   stat   --   列表   ext   

方法的重寫、覆蓋


在子類中可以根據需要對從父類中繼承來的方法進行改造—覆蓋方法(方法的重設、重寫),在程式執行時,子類的方法將覆蓋父類的方法。


覆蓋方法必須和被覆蓋方法具有相同的方法名稱、參數列表和傳回值類型


覆蓋方法不能使用比被覆蓋方法更嚴格的存取權限


覆蓋方法舉例(1)

public class Person {
  public String name;
  public int age;
  public String getInfo() {
    return "Name: "+ name + "\n" +"age: "+ age;
  }
}
public class Student extends Person {
  public String school;
  public String getInfo() {//覆蓋方法
    return "Name: "+ name + "\nage: "+ age + "\nschool: "+ school;
  }
  public static void main(String args[]) {
    Student s1=new Student();
    s1.name="Bob";
    s1.age=20;
    s1.school="school2";
    System.out.println(s1.getInfo()); //Name:Bob age:20 school:school2
  }
}


Person p1=new Person();
p1.getInfo();
//調用Person類的getInfo()方法
Student s1=new Student();
s1.getInfo();
//調用Student類的getInfo()方法
這是一種“多態性”:同名的方法,用不同的對象來區分調用的是哪一個方法。

 

覆蓋方法舉例(2)

class Parent {
  public void method1() {}
}

class Child extends Parent {
  private void method1() {}
  //非法,子類中的method1()的存取權限private比被覆蓋方法的存取權限public弱
}

public class UseBoth {
  public void doOtherThing() {
    Parent p1 = new Parent();
    Child p2 = new Child();
    p1.method1();
    p2.method1();
  }
}

 

Java類的設計----方法的重寫、覆蓋

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.