Prash
Prash

Reputation: 554

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 i.e 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();      
    }
}

Upvotes: 0

Views: 243

Answers (2)

M A
M A

Reputation: 72884

The class outterclass.innerclass is a static class field, which means you don't necessarily have an enclosing instance of 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.

With the class hierarchy you have, you'd have to make get_outer static (which requires making outer static as well).

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

Your innerclass is not an inner class. 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.

If innerclass was indeed inner, then you would have to instantiate it with an enclosing instance:

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

Then, in parent_class_info_fetch() you could write

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.

Upvotes: 1

Related Questions