Nested Classes Flashcards
Give 3 reasons why we use nested classes
Closely linked classes can be located in one place
It can increase encapsulation
Makes code more readable
How can enums be declared
As a separate class or a class member - not internally within a method
1) How are anonymous classes declared
2) Where can they be defined
3) When do we usually use anonymous classes
1) Without the keyword “class”; using the keyword “new” followed by the interface that you want to be implemented or the class that you want to extend
2) Within a method or within an argument of a method
3) When only instantiating the class once; they both declared and instantiated in a single statement
(You can’t pass parameters to it)
Local classes: What are they What modifiers can be used with them How do you access method local variables How do you access members of the outer class
1) Classes within methods
2) Cannot contain any modifiers
3) If they are declare final in the method that the local class is declared in
4) OuterClass.this.varName
Describe scoping (where things can be used in a program) of the key word “this” with inner and outer classes
Outer class instances: use OuterClass.this Inner class instances: use this
How do you create instances of inner classes from inside the outer class and from outside the outer class
Inside the outer class: Construct instance of inner class directly
Outside the outer class: Construct instance of outer class Construct instance of inner class using the newly constructed outer class
How would you create an object for the static nested class in the following code:
class Car { .... static class Gearbox { .... } }
Car.Gearbox varName = new car.GearBox();
How many files do inner classes produce on compilation
2:
OuterClass
OuterClass$InnerClass
Name two types of nested class and state the modifiers for outer and nested classes.
Static nested class => Doesn’t have access to instance members
Inner class => Has access to instance members
Modifiers for outer: public and default
Modifiers for nested: public, private, protected, default
How do nested class help overcome
The issue of having two tightly coupled classes that heavily rely on one another
How does encapsulation get in the way of classes being specialised
If we have two tightly coupled classes
They rely heavily on one another
Takes a lot of work to create functions to access each others members
Occurs frequently in GUI programming
Give 3 examples of OOP
Classes can be reused
Easy to maintain code
Can hide things that don’t need to be exposed