Nested Classes Flashcards
Within a class, define data and code.
Data - The instance variables of the class.
Code - The way in which the instance variables are operated on in methods.
What is a Static Nested Class? How are they instantiated?
A nested class that can’t access the non-static instances variables of the encapsulating class unless through a reference of the encapsulating class.
They are instantiated in a way such as A.B b = new A.B();
What is a Non-Static Nested Class? How does this class access members of the encapsulating class?
Known as an inner class. This class has access to all other members of the encapsulating class and can refer to them directly. It is instantiated through an instance of the encapsulating class.
What data can a static nested class access from the encapsulating class?
Static data and final data
Does the encapsulating class have access to the members of the nested class?
No
What issue does nested class resolve.
When two distinct classes are closely coupled, encapsulation can cause unnecessary overhead when accessing data of each other. Nested class resolves this.
What is a local class?
A local class is one that is defined within a code block such as a method.
What other members can local classes access?
They can access local members of the method which are declared as final. They can also access instance members of the outer class.
What is an anonymous class? When are they used?
Anonymous classes are declared and instantiated at the same time. They are used when the class is only needed once. They can either implement an interface or extend an existing class.