台灯开启不同颜色的灯亮
1、抽象类
package LESSON5; //用抽象类 台灯类 class Lamp{ private Buble buble;//类型为Buble的buble变量 public Buble getBuble() { return buble; } public void setBuble(Buble buble) { this.buble = buble; } public void on(){ buble.shine(); }; } abstract class Buble { public abstract void shine(); } class RedBuble extends Buble{ @Override public void shine() { System.out.println("red"); } } class GreenBuble extends Buble{ @Override public void shine() { System.out.println("green"); } } public class Exercise4 { public static void main(String[] args) { RedBuble re=new RedBuble(); GreenBuble gr=new GreenBuble(); Lamp la=new Lamp(); la.setBuble(re);//红灯 la.on();//输出red } }
2、接口无get,set方法
package LESSON7; class Lamp{ private Buble buble;//类型为Buble的buble变量 public void on(Buble buble){ buble.shine(); }; } interface Buble { //抽象方法 public void shine(); } class RedBuble implements Buble{ @Override public void shine() { System.out.println("red"); } } class GreenBuble implements Buble{ @Override public void shine() { System.out.println("green"); } } public class Exercise3 { public static void main(String[] args) { RedBuble re =new RedBuble (); GreenBuble gr=new GreenBuble(); Lamp la=new Lamp(); la.on(re); } }
3、接口有get,set方法
package LESSON6; class Lamp{ private Buble buble;//类型为Buble的buble变量 //或者不用设置属性和get,set方法直接将Buble buble当函数参数传给on(),调用时直接传入 public Buble getBuble() { return buble; } public void setBuble(Buble buble) { this.buble = buble; } public void on(){//(法2)public void on(Buble buble) buble.shine(); }; } interface Buble { public void shine(); } class RedBuble implements Buble{ @Override public void shine() { System.out.println("red"); } } class GreenBuble implements Buble{ @Override public void shine() { System.out.println("green"); } } public class Exercise1 { public static void main(String[] args) { RedBuble rb=new RedBuble(); GreenBuble gb=new GreenBuble(); Lamp la=new Lamp(); // la.on(rb);(法2)传入 la.setBuble(rb); la.on(); } }