2

I am trying to access private val inside an inner class, from the outer class without creating an instance of the inner class.

Is this even possible to access private inner class values from the outer class ?

Thanks in advance.

1
  • 3
    if it is an instance variable, then you need ... an instance. Commented Apr 13, 2013 at 10:11

2 Answers 2

5

If the field is static, you already can access it from the outer class even if it's private. You don't need an instance of either the inner or the outer class:

public class Clazz {
    class Inner {
        private static final int N = 10;
    }
    public static void main(String[] args) {
        System.out.println(Inner.N);
    }
}

If the inner class field is not static, it does not exist without an instance of the inner class. You can't access something that doesn't exist.

Sign up to request clarification or add additional context in comments.

1 Comment

[code] System.out.println("Details for computer"+this.serial_number+" "+new Video_Card (serial_number*100)) [/code] i've tried this but for some reason its prints out the below : Details for computer400 il.ac.shenkar.rec.Computer$Video_Card@67b56bda Details for computer400 il.ac.shenkar.rec.Computer$Video_Card@37bbea67
2

The short answer is no.

The longer answer is the following. Inner class is just a regular class that has "magic" reference to instance of its outer class that can be accessible via OuterClass.this. Creating of instance of outer class does not create instance of inner class automatically. This means that you cannot by definition access members of inner class from outer class without creating instance of inner class unless inner class itself and its members are static.

Indeed you can create one instance of outer class and 10 instances of corresponding inner class. How can you access member of inner class without creating its instance?

BTW the general advice: avoid creating inner classes unless you really need them.

1 Comment

Can you please elaborate on the advice "avoid creating inner classes unless you really need them"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.