用java编写一个程序用到接口,能用到接口概念的就行
答案:2 悬赏:0 手机版
解决时间 2021-11-24 15:21
- 提问者网友:川水往事
- 2021-11-23 21:33
用java编写一个程序用到接口,能用到接口概念的就行
最佳答案
- 五星知识达人网友:廢物販賣機
- 2021-11-23 21:56
代码如下:
public class Test {
public static void main(String[] args) throws Exception{
Lamp lamp = new Lamp(new RedBulb());
lamp.on();
lamp.setB(new GreenBulb());
lamp.on();
}
}
class Lamp{
private Bulb b;
public Lamp(Bulb b){
this.b = b;
}
public void on(){
b.light();
}
public void setB(Bulb b){
this.b = b;
}
}
interface Bulb{
void light();
}
class RedBulb implements Bulb{
@Override
public void light() {
System.out.println("Red light.");
}
}
class GreenBulb implements Bulb{
@Override
public void light() {
System.out.println("Green light.");
}
}
public class Test {
public static void main(String[] args) throws Exception{
Lamp lamp = new Lamp(new RedBulb());
lamp.on();
lamp.setB(new GreenBulb());
lamp.on();
}
}
class Lamp{
private Bulb b;
public Lamp(Bulb b){
this.b = b;
}
public void on(){
b.light();
}
public void setB(Bulb b){
this.b = b;
}
}
interface Bulb{
void light();
}
class RedBulb implements Bulb{
@Override
public void light() {
System.out.println("Red light.");
}
}
class GreenBulb implements Bulb{
@Override
public void light() {
System.out.println("Green light.");
}
}
全部回答
- 1楼网友:一把行者刀
- 2021-11-23 23:24
interface Eat {
void eat();
}
class Cat implements Eat {
public Cat(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void eat() {
System.out.println("Cat is eating.");
}
}
class Dog implements Eat {
public Dog(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public void eat() {
System.out.println("Dog is eating.");
}
}
public class Main{
public static void main(String args[]) {
Eat dog, cat;
dog = new Dog("A");
cat = new Cat("B");
dog.eat();
cat.eat();
}
}
/// 保存成Main.java
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯