Java接口练习

package 接口interface;
/*

  • 用接口实现关灯开灯
  • */
    public class Test {
    public static void main(String[] args) {
    Person Man=new Person(“魏”);
    Lamp lamp=new Lamp();
    Computer computer=new Computer(“Hasee”);
    Man.doOn(lamp);
    Man.doOn(computer);
    Man.doOff(computer);
    Man.doOff(lamp);
    }

}
//定义接口
interface On_Off{
int ON=1;
int OFF=0;
void on();
void off();
}

//定义灯继承接口
class Lamp implements On_Off{
int on=On_Off.OFF;
public void on(){
if(onOn_Off.OFF){
System.out.println(“开灯!”);
on=On_Off.ON;
}
else
System.out.println(“灯已经开了”);
}
public void off(){
if(on
On_Off.ON) {
System.out.println(“关灯!”);
on=On_Off.OFF;
}
else System.out.println(“灯已经关了”);
}
}

class Computer implements On_Off{
String logo;
int on=On_Off.OFF;
public Computer() {}
public Computer(String logo ) {
this.logo=logo;
}
public void setLogo(){
this.logo=logo;
}
public String getLogo(){
return logo;
}
public void on(){
if(onOn_Off.OFF) {
System.out.println(getLogo()+“正在开机》》》》》》”);
on=On_Off.ON;
}
else
System.out.println(“电脑已开机!!!”);
}
public void off(){
if(on
On_Off.ON) {
System.out.println(getLogo()+“正在关机》》》》》》”);
on=On_Off.OFF;
}
else
System.out.println(“已经关机!!!”);
}
}

class Person{
String name;
public Person() {}
public Person(String name) {
this.name=name;
System.out.println(“我是一名员工”+name);
}
public void doOn(On_Off o) {
System.out.println(name+“正在进行开操作”);
o.on();
}
public void doOff(On_Off o) {
System.out.println(name+“正在进行关操作”);
o.off();
}

}

猜你喜欢

转载自blog.csdn.net/weixin_44944367/article/details/89479316