用基類,介面,本類執行個體化對象的區別

來源:互聯網
上載者:User

廢話不多說了,代碼很清楚

寫個基類FatherClass.java

package com;public class FatherClass {public void speak(){System.out.println("Father method,speak() ");}public void sing(){System.out.println("Father method,sing() ");}public void jump(){System.out.println("Father method,jump() ");}public void run(){System.out.println("Father method,run() ");}}

寫個介面MotherInterface.java

package com;public interface  MotherInterface {public void cook();public void clean();public void love();}

寫具體的類SonClass.java

package com;public class SonClass extends FatherClass implements MotherInterface{@Overridepublic void cook() {// TODO Auto-generated method stubSystem.out.println("Son method cook()");}@Overridepublic void clean() {// TODO Auto-generated method stubSystem.out.println("Son method clean()");}@Overridepublic void love() {// TODO Auto-generated method stubSystem.out.println("Son method love()");}////////////////////重載基類方法///////////////////////////////////public void jump(){System.out.println("Son method,jump(),extends FatherClass ");}public void run(){System.out.println("Son method,run(),extends FatherClass");}////////////////////寫自己的方法///////////////////////////////////public void myMehtod(){System.out.println("Son method,myMehtod(),我自己的方法");}public static void main(String[] ss){//用基類執行個體對象,對象只有基類方法//(如果重載基類方法,走重載的那個方法)FatherClass fc=new SonClass();//用介面執行個體對象,對象只有介面方法//這些方法必須實現MotherInterface mi=new SonClass();//用本類執行個體對象,既有基類方法(有重載方法走重載的那個);//又有介面方法(介面方法必須實現);還有自己本類的專屬的方法。SonClass son=new SonClass();System.out.println("--------基類執行個體的對象fc------------");fc.speak();fc.sing();fc.jump();fc.run();System.out.println("--------介面執行個體的對象mi------------");mi.cook();mi.clean();mi.love();System.out.println("--------本類執行個體的對象son------------");son.speak();son.sing();son.jump();son.run();son.cook();son.clean();son.love();son.myMehtod();}}

控制台列印:

--------基類執行個體的對象fc------------
Father method,speak()
Father method,sing()
Son method,jump(),extends FatherClass
Son method,run(),extends FatherClass
--------介面執行個體的對象mi------------
Son method cook()
Son method clean()
Son method love()
--------本類執行個體的對象son------------
Father method,speak()
Father method,sing()
Son method,jump(),extends FatherClass
Son method,run(),extends FatherClass
Son method cook()
Son method clean()
Son method love()
Son method,myMehtod(),我自己的方法

聯繫我們

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