Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Core Java Basics. No Comments on Nested Class
4
(2)

In this article we will look at what is a nested class and how to define a nested class and access the nested class members in a Java program.

 

Java 1.1 added support for nested classes. A class defined as a member of another class definition is known as a nested class. A nested class can be either static or non-static. The non-static nested class is known as an inner class.

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


The enclosing class of an inner class can be called as an outer class. An inner class can access all the members of an outer class. But the outer class cannot access the inner class members. Inner classes and anonymous classes (inner classes without a name) are useful in event handling.

 

Below Java program demonstrates inner class (non-static nested class):

class Person
{
   int age;
   String name;
   class Details
   {
      public void showDetails()
      {
         System.out.println("Age: " + age);
         System.out.println("Name: " + name);
      }
   }
   public void show()
   {
      Details d = new Details();
      d.showDetails();
   }
   public static void main(String[] args)
   {
      Person p = new Person();
      p.age = 25;
      p.name = "surya";
      p.show();
   }
}

 

In the above example Details is the inner class and Person is the outer class.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

Leave a Reply

Your email address will not be published. Required fields are marked *