Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method in an inner class access a parent class method?

I'm not sure if my question title describes my situation aptly, so my apologies if it doesn't! Anyway, let's say I have the following code snippet (visibility is as stated):

public class ChildClass extends ParentClass {
    // more code
   private void myMethod() {
      MyClass mine = new MyClass() {
         public void anotherMethod() {
            // insert code to access a method in ParentClass
         }
      };
   }
}

Is it possible for code within anotherMethod() to access a protected method found in ParentClass? If so, how can this be done?

I've tried something like...

(ParentClass.this).parentMethod();

...but obviously it doesn't work due to scope issues.

like image 438
ohseekay Avatar asked Apr 19 '11 10:04

ohseekay


People also ask

Can you have an inner class inside a method and what variables can you access?

It can access any private instance variable of the outer class. Like any other instance variable, we can have access modifier private, protected, public, and default modifier. Like class, an interface can also be nested and can have access specifiers.

Can inner class access outer class method?

An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance. To instantiate an inner class, you must first instantiate the outer class.

Can child class access parent methods?

The reference holding the child class object reference will not be able to access the members (functions or variables) of the child class. This is because the parent reference variable can only access fields that are in the parent class.

Can inner class access?

You just need to write a class within a class. Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class. Following is the program to create an inner class and access it.


1 Answers

This compiles fine:

class MyClass {
}

class ParentClass {
    protected void parentMethod() {
    }
}

class ChildClass extends ParentClass {
    private void myMethod() {
        MyClass mine = new MyClass() {
            public void anotherMethod() {
                parentMethod(); // this works
            }
        };
    }
}
like image 94
WhiteFang34 Avatar answered Oct 18 '22 12:10

WhiteFang34