No enclosing instance of type StrategyTest(内部类) is accessible. Must qualify the allocation with an e

编程入门 行业动态 更新时间:2024-10-11 11:20:04

No enclosing instance of type StrategyTest(内<a href=https://www.elefans.com/category/jswz/34/1765347.html style=部类) 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

本文发布于:2024-02-07 06:24:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754245.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:部类   type   enclosing   instance   StrategyTest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!