提问者:小点点

多态性中的Helper类[重复]


我试图在helper类的帮助下学习多态性。 下面的例子是分别打开/关闭灯泡和风扇。 请帮我找出我的代码有什么问题。

代码1:

package xpolymWithAbstr;

import com.sun.codemodel.internal.JSwitch;

public interface XSwitch {
    void on();
    void off();
}

class Fan implements XSwitch {
    public void on() {
        System.out.println("fan is on");
    }

    public void off() {
        System.out.println("fan is off");
    }
}

class Bulb implements XSwitch{
        public  void on(){
            System.out.println("bulb is on");
        }
        public  void off(){
            System.out.println("bulb is off");
        }
}

代码2:

package xpolymWithAbstr;

class helper{
    static XSwitch demo(XSwitch f){
       return f;
   }
}


class abTest {
    public static void main(String[] args) {
        XSwitch s = helper.demo(f);
        s.on();
        s.off();
    }

}

问题在下面一行。

XSwitch s = helper.demo(f);

好心帮帮忙!!


共1个答案

匿名用户

f没有在main方法中声明。 试着申报FE。 xswitch f=new Bulb()之前使用“f”变量。 Helper类在这样的用法中没有太多意义(您基本上返回了作为参数传入的引用)