子類繼承父類,並重寫父類方法

來源:互聯網
上載者:User
例子1:父類:public class Person {public String name;public int age;public Person(String name,int age){  this.name=name;  this.age=age;}public Person() /*如果不寫這個建構函式,看看對類Student有什麼影響。*/{}public void getInfo(){System.out.println(name);System.out.println(age);}}子類:public class Student extends Person{String school;public Student(String name,int age,String school){super(name,age);this.school=school;}public Student(){}public void study() { System.out.println("學習非常棒。");}public static void main(String[] args){Person p=new Person();p.name="person";p.age=45;p.getInfo();Student s=new Student();s.name="student";s.age=26;s.getInfo();s.study(); }}例子2:在子類中可以根據需要對從父類中繼承來的方法進行改造----方法的覆蓋 ( 也叫重寫)。覆蓋方法必須和被覆蓋方法具有相同的方法名稱、參數列表和傳回值類型。例如例子1那個Student程式,它繼承了Person類的getInfo方法,這個繼承到的方法只能列印出學生的name和age,不能列印出學生專有的資訊,比如學校的名稱等,這時我們就應該在類Student中重新編寫一個getInfo方法,這就是方法的覆蓋。父類:package javatest;public class Person {public String name;public int age;public Person(String name,int age){  this.name=name;  this.age=age;} //如果不寫這個建構函式,看看對類Student有什麼影響。public Person(){}public void getInfo(){System.out.println(name);System.out.println(age);}}子類繼承父類:public class Student extends Person{String school;   //父類是沒有的,子類特有的public Student(String name,int age,String school){super(name,age);this.school=school;}public Student(){}public void study() { System.out.println("學習非常棒。");}public void getInfo(){ super.getInfo(); System.out.println(school);}public static void main(String[] args){Person p=new Person();p.name="person";p.age=45;p.getInfo();Student s=new Student();s.name="student";s.age=26;s.school="清華大學";s.getInfo();s.study(); }}

聯繫我們

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