Skip to main content

Java Exception Handling MCQ Test

  Loading…

Nested Class

 Nested Class:

- A nested class is a class that is defined within another class.

- It can be static or non-static and can access the members of the enclosing class.

- Nested classes are mainly used to logically group classes that are only used in one place or for better encapsulation and organization of code.


Example:

class Outer {

    private int outerVar;


    class Inner {

        void display() {

            System.out.println("Inner class method, outerVar = " + outerVar);

        }

    }

}


Explanation:

In the example above, the Inner class is nested within the Outer class. It has access to the private member `outerVar` of the Outer class.


Sample Use:

Nested classes are commonly used in scenarios where a class is only relevant within the context of another class. For example, in GUI programming, a Button class might be nested within a Window class because it only makes sense to have buttons within a window.


Analogy:

Imagine a company (Outer class) with various departments. Each department (Inner class) has its own set of employees and resources but operates under the umbrella of the company. Similarly, nested classes operate within the scope of the enclosing class but have their own functionalities and characteristics.

Comments

Popular posts from this blog

Iterators and Collections

In Java, iterators are objects that allow for sequential access to the elements of a collection. The Java Collections Framework provides the Iterator interface, which defines methods for iterating over collections such as lists, sets, and maps. Here's an explanation of iterators and their relationship with collections, along with examples: Iterator Interface: The Iterator interface provides methods to iterate over the elements of a collection sequentially: - boolean hasNext(): Returns true if there are more elements to iterate over. - E next(): Returns the next element in the iteration. - void remove():  Removes the last element returned by `next()` from the underlying collection (optional operation). Collections and Iterators: 1. Collection Interface:    - Collections represent groups of objects, such as lists, sets, and maps.    - They provide methods for adding, removing, and accessing elements. 2. Iterator Usage:    - Collections implement the Iter...

The Collection Interface.

  The Collection Interface.