37011

Accessing private instance variable of inner class from outer class

Question:

Why isn't this code working

public class BB { private class A { private int x; } public static void main(String[] args) { A a = new A(); a.x = 100; System.out.println(a.x); } }

while this code is working?

public class BB { private class A { private int x; } static int y = 3; public static void main(String[] args) { BB b = new BB(); b.compile(); System.out.println("y = "+ y); } public void compile() { A a = new A(); a.x = 100; System.out.println(a.x); System.out.println("y = "+ y); } }

In first code, When I am trying to refer to instance variable 'x' of inner class 'A' by an object of inner class 'a', I am getting an error saying that I'm using inner class in static context. There is no error while doing the same in some other method.

Answer1:

Your error has nothing to do with field access. Compilation fails for this line:

A a = new A();

Reason: you cannot instantiate an inner class without an enclosing instance, which is exactly what that line of code tries to do. You could write instead

A a = (new BB()).new A();

which would provide an enclosing instance inline. Then you will be able to access the private field as well.

Alternatively, just make the A class static, which means it does not have an enclosing instance.

Answer2:

private class A is like an instance member and we can not use instance member inside static method without making its object. So first we need to object of outer class than we can use instance inner class. And below code is working fine.

class BB { private class A { private int x; }

public static void main(String[] args) { BB bb = new BB(); BB.A a = bb.new A(); a.x = 100; System.out.println(a.x); }

}

Recommend

  • SonarQube: Cannot deactivate rule with missing quality profile
  • NUnit 3.0 TestCase const custom object arguments
  • How to add a focus style to an editable ComboBox in WPF
  • Reading a file into a multidimensional array
  • Diff between two dataframes in pandas
  • App restarts from wrong activity
  • Groovy: Unexpected token “:”
  • How to Cache Real-time Data?
  • Refering to the class itself from within a class mehod in Objective C
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Jetty Server not starting: Unable to establish loopback connection
  • Highlight one bar in a series in highcharts?
  • Spring Data JPA custom method causing PropertyReferenceException
  • Read text file and split every line in MSBuild
  • Possible to stop flickering java tooltip in heavyweight mode?
  • sending/ receiving email in Java
  • Weird JavaScript statement, what does it mean?
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • How do you troubleshoot character encoding problems?
  • Calling of Constructors in a Java
  • AT Commands to Send SMS not working in Windows 8.1
  • Is there a mandatory requirement to switch app.yaml?
  • How to format a variable of double type
  • Matrix multiplication with MKL
  • PHP: When would you need the self:: keyword?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • How do I configure my settings file to work with unit tests?
  • File not found error Google Drive API
  • How does Linux kernel interrupt the application?
  • Qt: Run a script BEFORE make
  • Linking SubReports Without LinkChild/LinkMaster
  • Is it possible to post an object from jquery to bottle.py?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Checking variable from a different class in C#
  • How to Embed XSL into XML
  • Converting MP3 duration time