package com.gezhi.interfaces;
/**
* 新建一個dog類實現接口livingable(狗吃和上廁所都是與生俱來的不該該寫成接口)
* @author square 涼
*
*/
public class Dog implements Livingable{
private String dogName;
private int dogAge;
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public int getDogAge() {
return dogAge;
}
public void setDogAge(int dogAge) {
this.dogAge = dogAge;
}
public void eat() {
System.out.println(dogName + " 具備吃東西的能力");
}
public void wc() {
System.out.println(dogName +" 具備上廁所的能力");
}
}
package com.gezhi.interfaces;
/**
* 人類,也實現接口吃飯上廁所的能力(固然吃和上廁所是與生俱來的能力,不該該寫成接口)
* @author square 涼
*
*/
public class People implements Livingable , ThinkAble{
private String peopleName;
private int peopleAge;
public String getPeopleName() {
return peopleName;
}
public void setPeopleName(String peopleName) {
this.peopleName = peopleName;
}
public int getPeopleAge() {
return peopleAge;
}
public void setPeopleAge(int peopleAge) {
this.peopleAge = peopleAge;
}
public void eat() {
System.out.println(peopleName + " 具備吃東西的能力");
}
public void wc() {
System.out.println(peopleName +" 具備上廁所的能力");
}
@Override
public void think() {
// TODO Auto-generated method stub
System.out.println(peopleName + " 具備思考的行爲");
}
}
package com.gezhi.interfaces;
/**
* 建一個服務類服務living這種能力
* @author square 涼
*
*/
public class Service {
/**
* 服務其餘生物的行爲
*/
public void serviceOther(Livingable lb) {
lb.eat();
lb.wc();
}
/**
* 人具備思考的行爲,這個方法主要傳我的(這裏傳了一個接口的參數,人類來實現它,主要運用了多態的特性)
* @param think
*/
public void ThinkOthers(ThinkAble think) {
think.think();
}
}
package com.gezhi.interfaces;
/**
* 思考的能力
* @author square 涼
*
*/
public interface ThinkAble {
void think();
}
package com.gezhi.interfaces;
/**
* 函數主入口類
* @author square 涼
*
*/
public class MainEnter {
public static void main(String[] args) {
// TODO Auto-generated method stub
Service se = new Service();//實例化服務類一個對象
People p = new People();//實例化人一個對象
p.setPeopleName("如花");//設置人名
se.serviceOther(p);//調用服務類的serviceOthers這個方法(原本這個參數是接口livingable的,這裏小轉大,傳我的這個實現了接口的對象)
Dog d = new Dog();//實例化一個狗類
d.setDogName("莽子");
se.serviceOther(d);
se.ThinkOthers(p);
}
}