部类) is accessible. Must qualify the allocation with an e"/>
No enclosing instance of type StrategyTest(内部类) is accessible. Must qualify the allocation with an e
No enclosing instance of type StrategyTest is accessible. Must qualify the allocation with an enclosing instance of type StrategyTest (e.g. x.new A() where x is an instance of StrategyTest).
翻译过来:无法访问StrategyTest类型的封闭实例。必须使用StrategyTest类型的封闭实例限定分配(例如x.new A(),其中x是战略测试)。
注:其中StrategyTest是内部类
我明明已经创建了一个实例 为什么还会显示我没有实例呢
之后才发现 原来主程序是主程序是public static void main(String[] args)
因为创建类时public class 没有加static 则该类成为了动态类
类的定义:类中的静态方法不能直接调用动态方法 因此报错
修改方法 最直接的是在创建类时 加上静态 static 如下:
下面展示的是我 单例模式的例子。
//创建一个策略实体类
public class StrategyTest {//创建一个接口public interface Strategy {public int operation(int num1, int num2);}public static class Operation implements Strategy{@Overridepublic int operationOne(int num1, int num2) {return num1 + num2;}}public static class OperationSubtract implements Strategy{@Overridepublic int operationTwo(int num1, int num2) {return num1 - num2;}}public static class Context {private Strategy strategy;public Context(Strategy strategy){this.strategy = strategy;}public int executeStrategy(int num1, int num2){return strategy.operation(num1, num2);}}public static void main(String[] args) {// TODO Auto-generated method stubContext context = new Context(new OperationOne()); System.out.println("2 + 1 = " + context.executeStrategy(2, 1));context = new Context(new OperationTwo()); System.out.println("2 - 1 = " + context.executeStrategy(2, 1));}}
策略模式代码部分参考:链接: .html.
更多推荐
No enclosing instance of type StrategyTest(内部类) is accessible. Must qualify the
发布评论