Nested Classes in Java
Overview
- Course: ECM2414 – Software Development
- Topic: Nested Classes (including Local and Anonymous Classes & Enumeration)
- Instructor: Prof. Solomon Oyelere
- Department: Computer Science, University of Exeter
Object-Oriented Programming Recap
OO Advantages
- Encapsulation/Information Hiding: Restricting access to internal components
- Inheritance: Deriving new classes from existing ones
- Polymorphism: Objects taking multiple forms
Issue with Encapsulation
- Classes should be specialized (include only code relating to specific function)
- Sometimes encapsulation gets in the way when dealing with tightly coupled classes:
- Classes rely heavily on each other’s members
- Lots of work required to create accessor functions
- Occurs frequently in GUI programming
What are Nested Classes?
Nested classes are classes defined within other classes to overcome encapsulation issues.
Types of Nested Classes
1. Static Nested Class
- Does NOT have access to instance members of outer class
- Accessed using outer class name:
OuterClass.StaticNestedClass
class OuterClass {
...
static class StaticNestedClass{
...
}
}2. Inner Class
- DOES have access to instance members of outer class
- More tightly coupled with outer class instance
class OuterClass {
...
class InnerClass {
...
}
} Access Modifiers for Nested Classes
- Standard outer class: Can only be declared
publicor package-private (default) - Nested classes: Can be declared with any modifier (
public,private,protected, package-private)
Why Use Nested Classes?
- Logical Grouping: Classes that are closely linked can be located in one place
- Increased Encapsulation: If one class is only used by another, the relationship becomes explicit
- More Readable Code: Clearer code organization
Example: Car and Engine
Car (private member) → Engine (hidden)
vs
Car (private member) → Engine (visible through nesting)
Inner Classes Details
Compilation
- Produces two class files on compilation:
OuterClass.classOuterClass$InnerClass.class
Construction Patterns
From Inside Outer Class:
Engine audiEngine = new Engine();From Outside Outer Class:
Car audi = new Car();
Car.Engine audiEngine = audi.new Engine();Scoping with this
this→ refers to inner class instanceOuterClass.this→ refers to outer class instance (when within inner class)
Static Nested Class Example
class Car {
...
static class Gearbox{
...
}
}
// Usage:
Car.Gearbox nestedObject = new Car.Gearbox();Local Classes
Characteristics
- Defined and exist solely within a block (usually a method)
- Cannot contain
public,protected,private, orstaticaccess modifiers - Cannot access method local variables unless they are
final - Can access all members of outer class instance
Example
public class LocalClassExample {
static String regularExpression = "[^0-9]";
public static void validatePhoneNumber(String phoneNumber1, String phoneNumber2) {
final int numberLength = 10; // Must be final to access in local class
class PhoneNumber {
String formattedPhoneNumber = null;
PhoneNumber(String phoneNumber) {
String currentNumber = phoneNumber.replaceAll(regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
public String getNumber() {
return formattedPhoneNumber;
}
}
PhoneNumber myNumber1 = new PhoneNumber(phoneNumber1);
...
}
}Anonymous Classes
Key Characteristics
- Most convoluted aspect of Java
- Classes declared without any class name
- Can be defined within a method
- Can be defined within method arguments
Basic Anonymous Class Example
public class HelloWorldAnonymousClasses {
interface HelloWorld {
public void greet();
public void greetSomeone(String someone);
}
public void sayHello() {
// Local class
class EnglishGreeting implements HelloWorld {
String name = "world";
public void greet() {
greetSomeone("world");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Hello " + name);
}
}
HelloWorld englishGreeting = new EnglishGreeting();
// Anonymous class
HelloWorld frenchGreeting = new HelloWorld() {
String name = "tout le monde";
public void greet() {
greetSomeone("tout le monde");
}
public void greetSomeone(String someone) {
name = someone;
System.out.println("Salut " + name);
}
};
}
}Anonymous Class Structure
HelloWorld frenchGreeting = new HelloWorld() {
// Class body implementation
};- Uses
newkeyword - Name of interface to implement or class to extend
- Note: When implementing interface, no constructor needed (empty parentheses)
Argument-Defined Anonymous Classes
Problem scenario:
class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(/* NEED AN INSTANCE OF FOO TO COMPILE! */);
}
}
interface Foo {
void foof();
}
class Bar {
void doStuff(Foo f) { }
}Solution with Anonymous Class:
class MyWonderfulClass {
void go() {
Bar b = new Bar();
b.doStuff(new Foo() {
public void foof() {
System.out.println("Hello");
}
});
}
}Enumerated Classes
Introduction
- Introduced in Java 5.0
- Useful for creating variables with specific ranges
- Example:
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Why Not Use Numbers (0-6)?
Problems with numeric approach:
- Must map between numeric value and meaning
- Must check for range errors
Enum Characteristics
- Not instantiated:
Day d = Day.TUESDAY; - Effectively static and final
- Can be declared as:
- Separate class
- Class member
- NOT internally within a method
Key Takeaways
Exercise Question
Why do we usually say “inner classes are more useful than static nested classes”?
Answer: B. Inner classes can access the instance members.
Explanation:
- A. Incorrect - Inner classes offer much more than just packing
- B. Correct - This is the key advantage of inner classes
- C. Incorrect - Access ease is not the main differentiator
- D. Partially correct but doesn’t explain why inner classes are MORE useful
Summary
- Nested Classes: Solution for tightly coupled classes
- Static Nested Classes: No access to outer instance members
- Inner Classes: Full access to outer instance members
- Local Classes: Defined within methods, limited scope
- Anonymous Classes: Declared without names, often used in arguments
- Enumerated Classes: Type-safe constants with meaningful names
Next Topics
The following lectures will focus on concurrency (threading) which utilizes inner classes in Java.
Tags
java nestedclasses innerclasses anonymousclasses enums oop softwaredevelopment