1. Write a program to create an outer class Person that has a private field name. Create an inner class Address inside the Person class that contains a private field address. Write a method displayInfo() in the inner class to print both name and address from the outer class?
Algorithm :
- Start
- Define a class named Person:
- Declare a private field name.
- Create a constructor that assigns a value to name.
- Inside Person, define a non-static inner class called Address:
- Declare a private field address.
- Create a constructor that assigns a value to address.
- Define a method displayInfo() that:
- Prints the name from the outer class Person.
- Prints the address from the inner class Address.
- In the main method (entry point of the program):
- Create an object of the outer class: Person person = new Person(“John”);
- Using the person object, create an instance of the inner class: Person.Address address = person.new Address(“1234 Elm Street”);
- Call the displayInfo() method of the Address object.
- End
Program :
class Person { private String name; public Person(String name) { this.name = name; } class Address { private String address; public Address(String address) { this.address = address; } public void displayInfo() { System.out.println(“Name: ” + name); // Accessing outer class field System.out.println(“Address: ” + address); // Accessing inner class field } } public static void main(String[] args) { Person person = new Person(“John”); Person.Address address = person.new Address(“1234 Elm Street”); address.displayInfo(); } } |
Output :
Name: John Address: 1234 Elm Street |
Explanation :
This program illustrates how a non-static inner class in Java can access both its own fields and the private fields of its enclosing outer class. The Person class holds a name, and its inner class Address holds an address. In the main method, an instance of Person is created first, then an Address object is created using that Person instance. When displayInfo() is called, it prints both the person’s name and their address, demonstrating inner class access to outer class members. |
2. Write a program to create a static inner class Employee within an outer class Department. The Employee class should have id, name, and salary attributes. Write a method to display the employee’s details?
Algorithm :
- Start
- Define a class Department.
- Inside it, define a static nested class Employee:
- Declare private fields: id, name, and salary.
- Create a constructor that initializes these fields.
- Define a method displayEmployeeDetails() to print the employee’s details.
- In the main method (within the Department class):
- Create an object of the static nested class: Department.Employee emp = new Department.Employee(…)
- Call emp.displayEmployeeDetails() to print the employee’s ID, name, and salary.
- End
Program :
class Department { static class Employee { private int id; private String name; private double salary; public Employee(int id, String name, double salary) { this.id = id; this.name = name; this.salary = salary; } public void displayEmployeeDetails() { System.out.println(“ID: ” + id); System.out.println(“Name: ” + name); System.out.println(“Salary: ” + salary); } } public static void main(String[] args) { Department.Employee emp = new Department.Employee(101, “Ram”, 50000); emp.displayEmployeeDetails(); } } |
Output :
ID: 101 Name: Ram Salary: 50000.0 |
Explanation :
This program demonstrates the use of a static nested class in Java through the Department class, which contains a static inner class called Employee. The Employee class has attributes such as id, name, and salary, along with a method displayEmployeeDetails() to print these values. Being a static class, Employee can be instantiated directly using the outer class name without needing an instance of Department. In the main method, an Employee object is created and initialized with sample data, and then the details are displayed using the method call. |
3. Write a Java program where a non-static inner class Calculator can access the private field number in the outer class MathOperations. The inner class should implement methods for addition and subtraction of a given number and display the results?
Algorithm :
- Start
- A class MathOperations is defined with an instance variable number.
- An inner class Calculator is defined inside MathOperations with two methods: add() and subtract().
- In the main() method, an object of MathOperations is created with the value 10.
- Using that object, an instance of the inner class Calculator is created.
- The add() method is called with argument 5, which prints the sum of 10 + 5.
- The subtract() method is called with argument 3, which prints the result of 10 – 3.
- End
Program :
class MathOperations { private int number; public MathOperations(int number) { this.number = number; } class Calculator { public void add(int num) { System.out.println(“Addition: ” + (number + num)); } public void subtract(int num) { System.out.println(“Subtraction: ” + (number – num)); } } public static void main(String[] args) { MathOperations mathOp = new MathOperations(10); MathOperations.Calculator calc = mathOp.new Calculator(); calc.add(5); // Output: Addition: 15 calc.subtract(3); // Output: Subtraction: 7 } } |
Output :
Addition: 15 Subtraction: 7 |
Explanation :
This Java program demonstrates the use of a non-static inner class. The MathOperations class contains an integer variable and an inner class Calculator that performs basic arithmetic operations using the outer class’s variable. The main() method creates an instance of the outer class with the value 10, and then uses it to instantiate the Calculator inner class. The add() method adds 5 to 10, printing Addition: 15, while subtract() subtracts 3 from 10, printing Subtraction: 7. The inner class directly accesses the outer class’s private variable number, showcasing tight coupling. |
4. Write a program to create an interface Shape with methods area() and perimeter() implement the Shape interface using an anonymous inner class inside the main method to calculate the area and perimeter of a rectangle. The length and width of the rectangle should be passed as parameters?
Algorithm :
- Start
- Define an interface Shape with two methods: area() and perimeter().
- In the main method, create an anonymous inner class implementing Shape.
- Inside the anonymous class, define length = 5 and width = 3.
- Override the area() method to return length * width.
- Override the perimeter() method to return 2 * (length + width).
- Call rectangle.area() and rectangle.perimeter() and print the results.
- End
Program :
interface Shape { double area(); double perimeter(); } public class ShapeTest { public static void main(String[] args) { Shape rectangle = new Shape() { private double length = 5; private double width = 3; @Override public double area() { return length * width; } @Override public double perimeter() { return 2 * (length + width); } }; System.out.println(“Area: ” + rectangle.area()); System.out.println(“Perimeter: ” + rectangle.perimeter()); } } |
Output :
Area: 15.0 Perimeter: 16.0 |
Explanation :
This program defines an interface Shape with area() and perimeter() methods. In the main method, an anonymous inner class is used to implement this interface for a rectangle. The rectangle’s dimensions are fixed at length 5 and width 3. The overridden area() method returns the product of length and width, resulting in 15. The perimeter() method returns the sum of all sides, giving 16. This approach allows implementing the interface directly without creating a separate named class. |
5. Write a Java program that uses a local inner class inside a method. The local inner class should take two integers as input and perform the operation of multiplying them. The result should be printed inside the method?
Algorithm :
- Start
- The Calculator class defines a method multiplyNumbers(int a, int b).
- Inside multiplyNumbers, a local inner class named Multiplier is defined.
- The Multiplier class contains a method multiply() that prints the product of a and b.
- An object of the Multiplier class is created.
- The multiply() method is called, which calculates and prints the result.
- In main, an instance of Calculator is created and multiplyNumbers(4, 5) is called.
- End
Program :
public class Calculator { public void multiplyNumbers(int a, int b) { class Multiplier { public void multiply() { System.out.println(“Multiplication Result: ” + (a * b)); } } Multiplier multiplier = new Multiplier(); multiplier.multiply(); } public static void main(String[] args) { Calculator calc = new Calculator(); calc.multiplyNumbers(4, 5); // Output: Multiplication Result: 20 } } |
Output :
Multiplication Result: 20 |
Explanation :
This program demonstrates the use of a local inner class in Java. The Calculator class contains a method multiplyNumbers, where a local inner class Multiplier is defined. This inner class can access the method parameters a and b directly. When the method multiply() is called, it prints the result of multiplying a and b. In the main method, an object of Calculator is created, and the multiplication operation is triggered with values 4 and 5. This results in the output “Multiplication Result: 20”, showcasing encapsulation of logic within a method. |
6. Write a Java program where an inner class Printer accesses the outer class Book’s title using this keyword?
Algorithm :
- Start
- Define a class Book with a private field title.
- Create a constructor for Book that initializes the title field.
- Define a non-static inner class Printer inside Book.
- In the Printer class, define a method printTitle() that accesses and prints Book.this.title.
- In the main method:
- Create a Book object with the title “Java Programming”.
- Create a Printer object using the book object.
- Call printTitle() to display the title.
- End
Program :
class Book { private String title; public Book(String title) { this.title = title; } class Printer { public void printTitle() { System.out.println(“Book title: ” + Book.this.title); } } public static void main(String[] args) { Book book = new Book(“Java Programming”); Book.Printer printer = book.new Printer(); printer.printTitle(); // Output: Book title: Java Programming } } |
Output :
Book title: Java Programming |
Explanation :
This program demonstrates the use of a non-static inner class in Java. The Book class contains a private title field and a nested inner class Printer. The inner class can access the outer class’s private members, which is shown in the printTitle() method using Book.this.title. In the main method, a Book object is created with the title “Java Programming”, and an associated Printer object is created through the outer object. The printTitle() method is then called to display the book’s title. This highlights how inner classes can encapsulate behavior tied closely to an outer class’s instance. |
7. Write a program to create a class Bank that contains a non-static inner class Account. The Account class should have methods to deposit, withdraw, and check balance. The outer class should allow for managing accounts, and it should print account details?
Algorithm :
- Start
- Define a class Bank with a private member bankName and a constructor to initialize it.
- Inside Bank, define a non-static inner class Account with a balance field and its own constructor.
- deposit(double) to increase the balance,
- withdraw(double) to reduce balance if sufficient,
- getBalance() to return the balance,
- accountDetails() to print bank name and current balance.
- In main(), create a Bank object with the name “MyBank”.
- Create an Account object via the bank object with an initial balance of 1000.
- Call deposit(500) → balance becomes 1500.
- Call withdraw(300) → balance becomes 1200.
- Call accountDetails() → prints bank name and current balance.
- End
Program :
class Bank { private String bankName; public Bank(String bankName) { this.bankName = bankName; } class Account { private double balance; public Account(double initialBalance) { this.balance = initialBalance; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) { if (balance >= amount) { balance -= amount; } else { System.out.println(“Insufficient balance”); } } public double getBalance() { return balance; } public void accountDetails() { System.out.println(“Bank: ” + bankName); System.out.println(“Balance: ” + balance); } } public static void main(String[] args) { Bank bank = new Bank(“MyBank”); Bank.Account account = bank.new Account(1000); account.deposit(500); account.withdraw(300); account.accountDetails(); // Output: Bank: MyBank, Balance: 1200.0 } } |
Output :
Bank: MyBank Balance: 1200.0 |
Explanation :
This program demonstrates how a non-static inner class can access the outer class’s members. The Bank class has a field bankName, while the inner class Account handles account operations like deposit, withdrawal, and showing details. The main() method creates a Bank object and then an Account with an initial balance of 1000. It then performs a deposit of 500 and a withdrawal of 300, resulting in a final balance of 1200. The accountDetails() method is used to display the bank name and the updated balance. This setup models a real-world banking scenario where accounts belong to a specific bank and perform typical transactions. |