Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Inner Object Class Variables

In my main class, I have an inner class called Shape which extends JButton. This inner class has a private char variable that goes by the name of CUBE.

I wrote getters and setters for it. I noticed that in the main method, instead of using:

(instance of Shape).getCUBE(); 

I can access it by using:

(instance of Shape).CUBE

Does this happen because CUBE is ultimately in the same class as main?

Is it necessary by java programming conventions that I write getters and setters for such an inner class?

like image 382
Zenos Avatar asked Jul 26 '26 12:07

Zenos


1 Answers

Does this happen because CUBE is ultimately in the same class as main?

No, it works because the language specification says it does. It will end up as a separate class as far as the JVM is concerned, but extra package-level methods will be created to allow the outer class to appear to violate the normal rules.

The relevant section of the language specification is in 6.6.1:

Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.

(Emphasis mine.)

So actually, even peer nested classes have access to private members. Sample code:

public class Test {

    public static void main(String[] args) {
        First first = new First(10);
        Second second = new Second(first);
        System.out.println(second.getValueFromFirst());
    }

    private static class First {        
        private final int value;

        private First(int value) {
            this.value = value;
        }
    }

    private static class Second {
        private final First first;

        private Second(First first) {
            this.first = first;
        }

        private int getValueFromFirst() {
            return first.value;
        }
    }
}

If you look at the generated classes (with javap -c Test$First and javap -c Test$Second you'll see the synthetic methods generated by the compiler.

like image 117
Jon Skeet Avatar answered Jul 28 '26 02:07

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!