Understandnig Java Inner Classes
Member Inner Classes
public class ComputerSystem {
private String systemName = "Desktop";
private void displayMessage() {
System.out.println("This is a computer system");
}
class HardwareComponent {
String memory = "32GB";
String storage = "SSD";
void showDetails() {
System.out.println(systemName);
displayMessage();
}
}
}
public class Application {
public static void main(String[] args) {
ComputerSystem system = new ComputerSystem();
ComputerSystem.HardwareComponent component = system.new HardwareComponent();
component.showDetails();
}
}
Static Nested Classes
public class ComputerSystem {
private static String manufacturer = "TechCorp";
private String systemName = "Desktop";
private void displayMessage() {
System.out.println("This is a computer system");
}
static class Peripheral {
String display = "LED";
void showInfo() {
System.out.println(manufacturer);
}
}
}
// Usage
ComputerSystem.Peripheral peripheral = new ComputerSystem.Peripheral();
Local Inner Classes
public class ComputerSystem {
int processData(int value) {
class LocalComponent {
String brandA = "Dell";
String brandB = "HP";
}
LocalComponent component = new LocalComponent();
return value * 2;
}
}
Anoynmous Inner Classes
// Implementing interface with anonymous class
new DeviceOperation() {
@Override
public void powerOn() {
System.out.println("Device powered on");
}
@Override
public void powerOff() {
System.out.println("Device powered off");
}
@Override
public void restart() {
System.out.println("Device restarting");
}
};
public interface DeviceOperation {
void powerOn();
void powerOff();
void restart();
}