Java Nested classes
Overview
Java allows you to define a class within another class. Such a class is called a nested class or inner class.
public class OuterClass { ... private class InnerClass { ... } }
Nested classes are divided into two: non-static and static. Nested classes that are declared with static keyword are called as static nested classes.
Non-static nested classes are known as inner classes.
Example of a static nested class
Here’s a simple example of a static nested class:
public class OuterClass { ... static class NestedStatic { ... } }
An inner class can only be accessed through an instance of the outer class. Even though a non-static inner class has a separate class file created for it when the outer class is compiled, that does not mean that we can just access the inner class like any other normal class.
Example
In this post, we will see code examples of an inner class. Book the outer class, BookCost is the inner class. A sample driver program showing the usage.
import java.text.DecimalFormat; public class Book { private String description; private String author; private int bookID; private BookCost cost; /** * Book class constructor **/ public Book(String author,String desc,int id, double wholesale, double retail) { this.description = desc; this.author=author; this.bookID = id; cost = new BookCost(wholesale, retail); } /** * Book class toString method */ public String toString() { String str; // To hold a descriptive string. // Create a DecimalFormat object to format output. DecimalFormat dollar = new DecimalFormat("#,##0.00"); // Create a string describing the item. str = "Book Author: " + author + "\nDescription: " + description + "\nBook Id: " + bookID + "\nBook Wholesale Cost: $" + dollar.format(cost.getWholesale()) + "\nBook Retail Price: $" + dollar.format(cost.getRetail()); // Return the string. return str; } /** * BookCost Inner Class */ private class BookCost { public double wholesale; public double retail; public double getWholesale() { return wholesale; } public void setWholesale(double wholesale) { this.wholesale = wholesale; } public double getRetail() { return retail; } public void setRetail(double retail) { this.retail = retail; } /** * BookCost class constructor */ public BookCost(double w, double r) { wholesale = w; retail = r; } } }
Demo
/** * This program demonstrates the Book class, * which has an inner class. */ public class BookClassDemo { public static void main(String[] args) { // Create a Book object. Book book = new Book("Stephen Hawking","Brief History of Time", 1033,10.50, 10.75); // Display the book's information. System.out.println(book); } }
Output:
Book Author: Stephen Hawking
Description: Brief History of Time
Book Id: 1033
Book Wholesale Cost: $10.75
Book Retail Price: $10.50
—
Java Tutorials
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
For more information on Java, visit the official website :