In advanced Java applications, inner classes provide a unique way to organize code while maintaining strict encapsulation. This project demonstrates how a non-static inner class can directly access the private fields of its outer class. The Greeting class, nested within Person, retrieves the private userName variable without requiring public getters. This ensures that sensitive user data remains hidden from the rest of the application while remaining fully functional for internal components.
- Inner Class Privacy: Demonstrated that inner classes bypass standard access restrictions of the outer class.
- Instance Binding: Used the mandatory
outerInstance.new InnerClass()syntax for instantiation. - Encapsulated State: Maintained
userNameas a private field within thePersonclass. - Contextual Behavior: The greeting logic is logically grouped within the entity it describes.
- Java 8+ (Non-static Inner Classes, Private Field Access, Object Coupling)
- Person: The outer class holding protected user identity.
- Greeting: The inner class providing specialized interaction logic.
- AssistantApp: The entry point simulating the AI assistant's activation.
Hello, Anna
Project Structure:
JavaBasics_Task_265/ ├── src/ │ └── com/yurii/pavlenko/ │ ├── Person.java │ └── AssistantApp.java └── README.md
Code
package com.yurii.pavlenko;
public class AssistantApp {
public static void main(String[] args) {
Person person = new Person("Anna");
Person.Greeting greeting = person.new Greeting();
greeting.sayHello();
}
}package com.yurii.pavlenko;
public class Person {
private String userName;
public Person(String userName) {
this.userName = userName;
}
public class Greeting {
public void sayHello() {
System.out.println("Hello, " + userName);
}
}
}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