In nested object structures, an inner class often needs to reference the state of its parent instance. This project demonstrates the use of a Non-static Inner Class (Room) within an outer class (House). It highlights the Outer.this syntax, which allows the inner class to explicitly access the outer class's private fields. This is essential for distinguishing between local instance data and the broader context provided by the parent object.
- Inner Class Nesting: Implemented
RoominsideHouseto model a physical relationship. - Outer Reference: Used
House.this.houseAddressto retrieve data from the parent instance. - Constructor Initialization: Both classes use private fields initialized via their respective constructors.
- Access Modifiers: Demonstrated that inner classes have full access to private members of the outer class.
- Java 8+ (Inner Classes, Scoping and Shadowing, Encapsulation)
- House: The outer class representing the global context (address).
- Room: The inner class representing a specific sub-entity (identifier).
- HouseApp: The entry point demonstrating the linked instantiation of House and Room.
Room: Master Bedroom
House: Sunny Valley Lane
Project Structure:
JavaBasics_Task_267/
├── src/
│ └── com/yurii/pavlenko/
│ ├── House.java
│ └── HouseApp.java
└── README.md
Code
package com.yurii.pavlenko;
public class HouseApp {
public static void main(String[] args) {
House house = new House("Sunny Valley Lane");
House.Room room = house.new Room("Master Bedroom");
room.printAddresses();
}
}package com.yurii.pavlenko;
public class House {
private String houseAddress;
public House(String houseAddress) {
this.houseAddress = houseAddress;
}
public class Room {
private String roomIdentifier;
public Room(String roomIdentifier) {
this.roomIdentifier = roomIdentifier;
}
public void printAddresses() {
System.out.println("Room: " + this.roomIdentifier);
System.out.println("House: " + House.this.houseAddress);
}
}
}This project is licensed under the MIT License.
Copyright (c) 2026 Yurii Pavlenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files...
License: MIT