简体   繁体   English

如何在继承内部类的子类中访问外部类成员

[英]how to access the outer class members in subclass wherin inner class is inherited

//below class is the example where in subclass extends the innerclass and from the subclass i am trying to access the methods of outer class ie encapsulating class of inner class. //下面的类是在子类中扩展内部类的示例,我试图从子类访问外部类的方法,即封装内部类的类。

package innerClass;

public class outterclass {
    private int outer=24;
    protected int get_outer(){
        return outer;
    }
    protected static class innerclass{
        private int outer=25;
        protected int get_outer(){
            return outer;
        }
    }
}
package innerClass;

public class subclass_B extends outterclass.innerclass {

    void parent_class_info_fetch(){
        System.out.println(get_outer());
        //i want to access the outer class get_outer method and how do i achieve that?
    }
    public static void main(String[] args) {
        InheritanceStaticInnerClass_B isb=new InheritanceStaticInnerClass_B();
        isb.parent_class_info_fetch();      
    }
}

Your innerclass is not an inner class. 你的innerclass是不是一个内部类。 It is a static nested class and bears no special relationship to its enclosing class. 它是一个静态嵌套类,与其封闭类没有特殊关系。 You cannot reach an instance of the enclosing class because no such instance is available to innerclass or its subclasses. 您无法到达封闭类的实例,因为innerclass类或其子类没有此类实例。

If innerclass was indeed inner, then you would have to instantiate it with an enclosing instance: 如果innerclass确实是内部类,那么您必须使用一个封闭的实例来实例化它:

outterclass outer = new outerclass();
subclass_B b = outer.new subclass_B();

Then, in parent_class_info_fetch() you could write 然后,在parent_class_info_fetch()您可以编写

outterclass.this.get_outer()

to reach that method. 达到那种方法。

Of course, there would be several layers of bad practices in such code, so consider this just an academic execrise. 当然,此类代码中会存在几层不良做法,因此请仅将这视为学术执行。

You should also learn about the basic naming conventions in Java. 您还应该了解Java中的基本命名约定。

The class outterclass.innerclass is a static class field, which means you don't necessarily have an enclosing instance of outterclass . outterclass.innerclass类是一个静态类字段,这意味着您不必包含outterclass的封闭实例。 On the other hand, the method get_outer of outterclass is an instance method, so you'll need the enclosing instance to call it. 另一方面, get_outeroutterclass方法是一个实例方法,因此您需要封闭的实例来调用它。

With the class hierarchy you have, you'd have to make get_outer static (which requires making outer static as well). 有了类层次结构,就必须使get_outer静态(这也需要使outer静态)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM