“Non-static variable this cannot be referenced from a static context” when creating an object

Make ShowBike.Bicycle static. public class ShowBike { private static class Bicycle { public int gear = 0; public Bicycle(int v) { gear = v; } } public static void main() { Bicycle bike = new Bicycle(5); System.out.println(bike.gear); } } In Java there are two types of nested classes: “Static nested class” and “Inner class”. Without … Read more

Inner class within Interface

Yes, we can have classes inside interfaces. One example of usage could be public interface Input { public static class KeyEvent { public static final int KEY_DOWN = 0; public static final int KEY_UP = 1; public int type; public int keyCode; public char keyChar; } public static class TouchEvent { public static final int … Read more

Why is an anonymous inner class containing nothing generated from this code?

I’m using polygenelubricants’s smaller snippet. Remember there’s no concept of nested classes in the bytecode; the bytecode is, however, aware of access modifiers. The problem the compiler is trying to circumvent here is that the method instantiate() needs to create a new instance of PrivateInnerClass. However, OuterClass does not have access to PrivateInnerClass‘s constructor (OuterClass$PrivateInnerClass … Read more

Why would one use nested classes in C++?

Nested classes are cool for hiding implementation details. List: class List { public: List(): head(nullptr), tail(nullptr) {} private: class Node { public: int data; Node* next; Node* prev; }; private: Node* head; Node* tail; }; Here I don’t want to expose Node as other people may decide to use the class and that would hinder … Read more