69.5k views
5 votes
Can an instantiation of an inner class access the methods of the class outside?

a) Yes
b) No

1 Answer

4 votes

Final answer:

Yes, an instantiation of an inner class can access methods of the parent, or 'outer', class. This allows the inner class to interact with the outer class's members, including private ones.

Step-by-step explanation:

Can an instantiation of an inner class access the methods of the class outside? The answer is a) Yes. An inner class is a class defined within another class, and instances of an inner class have the ability to access the methods and fields of the outer class, even if they are declared private. However, this is not a two-way relationship; the outer class does not have inherent access to the members of the inner class unless it holds a reference to an instance of the inner class.

In Java, for example, if you instantiate an inner class within the method of an outer class, that instance can call the methods from the outer class directly. Here's a simplistic example:

public class OuterClass {
private int outerNumber = 10;
public void outerMethod() {
System.out.println("Outer method.");
}
class InnerClass {
public void innerMethod() {
outerMethod(); // Accessing outer class method
System.out.println("Outer number is: " + outerNumber); // Accessing outer class field
}
}
}
User Timaschew
by
7.8k points