Java Inner Class Accessing Outer Class Members Example
Java Nested Classes: Exercise-5 with Solution
Inner Class Accessing Outer Class Members:
Write a Java program to create an outer class called Library with an instance variable libraryName. Create an inner class Book with a method getLibraryName() that returns the name of the library. Instantiate the Book class and call the getLibraryName() method.
Sample Solution:
Java Code:
Library.java
// Class Library
public class Library {
// Instance variable libraryName
private String libraryName;
// Constructor to initialize libraryName
public Library(String libraryName) {
this.libraryName = libraryName;
}
// Inner class Book
public class Book {
// Method getLibraryName that returns the name of the library
public String getLibraryName() {
// Accessing the outer class's instance variable libraryName
return libraryName;
}
}
// Main method to demonstrate inner class accessing outer class members
public static void main(String[] args) {
// Creating an instance of Library
Library myLibrary = new Library("Central Library");
// Creating an instance of the inner class Book
Library.Book myBook = myLibrary.new Book();
// Calling the getLibraryName method and printing the result
System.out.println("Library Name: " + myBook.getLibraryName());
}
}
Output:
Library Name: Central Library
Explanation:
- Class Library: The outer class with an instance variable libraryName.
- Constructor Library(String libraryName): Initializes the libraryName.
- Inner class Book: Contains the method getLibraryName().
- Method getLibraryName(): Returns the libraryName of the outer class.
- Main method: Demonstrates the usage of the inner class by creating instances of Library and Book and calling the getLibraryName() method
Note on Java Nested Classes:
Java nested classes allow inner classes to access the members of their outer class. In this exercise, the Book class is an inner class of the Library class and can access the 'libraryName' variable directly. This demonstrates the close relationship between inner and outer classes, enhancing encapsulation and code organization by keeping related functionalities together.
Java Code Editor:
Improve this sample solution and post your code through Disqus.
Java Static Members Previous: Java Anonymous Class Implementing an Interface Example.
Java Static Members Next: Java Static Nested Class and Static Methods Example.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/nested-classes/java-nested-classes-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics