使用私有构造函数访问私有内部类的重写方法

时间:2017-02-23 06:54:39

标签: java inner-classes access-modifiers

请找到以下代码段: 课程规则

public class Rules {

    public static final JarvisFilterRule FILTER = new JarvisFilterRule();

    private static class JarvisFilterRule extends RelOptRule {
        private JarvisFilterRule() {
            super(operand(Filter.class, operand(Query.class, none())));
        }

        public void onMatch(RelOptRuleCall call) {
        // do something
        }
    }
}

类RelOptRule

public abstract class RelOptRule {

  /**
   * Description of rule, must be unique within planner. Default is the name
   * of the class sans package name, but derived classes are encouraged to
   * override.
   */
    protected final String description;
    public abstract void onMatch(RelOptRuleCall call);
}

我的问题是:如何访问嵌套类Rules.JarvisFilterRule的onMatch()方法?

2 个答案:

答案 0 :(得分:0)

private关键字的目的是阻止访问需要由声明它的类专门使用的类成员。

在您的情况下,Rules类将JarvisFilterRule定义为private内部类,其目的是仅为Rules类知道其实现。

如果您希望访问其他课程中的JarvisFilterRule::onMatch()方法,则需要将private JarvisFilterRule修饰符替换为public或移动内部类{{ 1}}到它自己的单独文件,并使其成为JarvisFilterRule类。像这样:

  

JarvisFilterRule .java

public

- 或 -

public class JarvisFilterRule extends RelOptRule {
        public JarvisFilterRule() {
            super(operand(Filter.class, operand(Query.class, none())));
        }

        public void onMatch(RelOptRuleCall call) {
        // do something
        }
    }

希望这有帮助!

答案 1 :(得分:0)

JarvisFilterRule

Console.WriteLine(JsonConvert.SerializeObject( System.Threading.Thread.CurrentThread, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Serialize })); 不是内部类。 Java中的内部类是一个非静态的嵌套类。