Java

Inner classes in Java

Inner classes in Java

Inner classes are classes that are defined within another class. 
● Member inner classes: These classes are defined within another class and have access to the instance variables and methods of the enclosing class. 
● Local inner classes: These classes are defined within a method and have access to the final variables of the enclosing method. 
● Anonymous inner classes: These classes are defined without a name and are typically used to provide a single-method implementation. 

Let us look into the example of these three: 

Member Inner Class

class MyOuterClass { 
private int x; 
class MyInnerClass { 
public void printX() { 
System.out.println(x); 
} 
} 
} 

This example defines an inner class called MyInnerClass within the MyOuterClass. The MyInnerClass has access to the private variable x of the MyOuterClass. 

Local Inner Class:

class MyOuterClass { 
public void printSquare(final int x) { 
class Square { 
public void print() { 
System.out.println(x*x); 
} 
} 
Square s = new Square(); 
s.print(); 
} 
} 

This example defines a local inner class called Square within the printSquare method of the MyOuterClass. The Square class has access to the final variable x of the printSquare method. 

Anonymous Inner Class: 

class MyOuterClass { 
public void performAction(final int x) { 
new Action() { 
public void execute() { 
System.out.println(x*x); 
} 
}.execute(); 
} 
interface Action { 
public void execute(); 
} 
} 

This example defines an anonymous inner class that implements the Action interface within the performAction method of the MyOuterClass. The anonymous inner class has access to the final variable x of the performAction method. 
Inner classes are often used to encapsulate functionality within a class or to provide additional functionality to a class. They can also be useful when working with events, as they can be used to define event handlers. 
 

Top course recommendations for you

    Data Structures in C
    2 hrs
    Beginner
    181.8K+ Learners
    4.39  (13192)
    Introduction to R
    1 hrs
    Beginner
    164.2K+ Learners
    4.56  (8770)
    Excel for Beginners
    5 hrs
    Beginner
    1.3M+ Learners
    4.48  (66589)
    Excel for Intermediate Level
    3 hrs
    Intermediate
    213.5K+ Learners
    4.54  (11421)
    My SQL Basics
    5 hrs
    Beginner
    264.6K+ Learners
    4.46  (14007)
    Android Application Development
    2 hrs
    Beginner
    161.3K+ Learners
    4.42  (7049)
    OOPs in Java
    2 hrs
    Beginner
    115.4K+ Learners
    4.45  (6770)
    Building Games using JavaScript
    2 hrs
    Beginner
    33.5K+ Learners
    4.46  (655)
    Introduction to DevOps
    3 hrs
    Beginner
    68.8K+ Learners
    4.56  (4346)
    Introduction To AngularJS
    2 hrs
    Beginner
    25.5K+ Learners
    4.54  (1090)