Syntax:
class Java_Outer_Class{ //code class Java_Inner_Class_Or_Nested Class{ //code } }
1) Nested classes represents a special type of relationship that it can access all the members(data members and methods) of outer class including private
2) Nested classes are used to deelop more readable and maintainable code because it logically group classes and interfaces in one place only.
3)Code optimization:It requires less code to write.
Types of Nested classes:
1. Non-static nested class(inner class)
a) Member inner class
b) Anonymouse inner class
c)Local inner class
2. Static nested class
Non static nested class is known as inner class
Java member inner class:
class Outer{ //code class inner{ //code } }
example:
public class TestMemberOuter1 { private int data=30; class Inner{ void msg() { System.out.println("data is: "+data); } } public static void main(String[] args) { TestMemberOuter1 obj=new TestMemberOuter1(); TestMemberOuter1.Inner in=obj.new Inner(); in.msg(); } }
Java Anonymous Inner Class
A class that have no name is known as anonymous inner class in java.It should be used if you have to override method of class or interface. Java anonymou inner class can be created by two ways:
1.Class(may be abstract or concrete)
2. Interface
Java anonymlus inner class example using class
abstract class Person { abstract void eat(); } class TestAnonymousInner{ public static void main(String[] args) { Person p=new Person(){ void eat(){ System.out.println("nice fruits"); } }; p.eat(); } }
Internal working of given code:
Person p=new Person(){ void eat(){ System.out.ptinln("nice fruits"); } }
1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
2. An object of anonymous class is created that is referred by p reference variable of Person type.
Internal class generated by the compiler:
import java.io.PrintStream; static class TestAnonymousInner$1 extends Person { TestAnonymouseInner$1(){} void eat() { System.out.println("nice fruits"); } }
Local inner class:
A class created inside a method is called local inner class in java.If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
example:
public class localInner1{ private int data=30;//intsance variable void display() { class Local{ void msg(){ System.out.println(data); } Local I=new Local(); I.msg(); } } public static void main(String[] args) { localInner1 obj=new localInner1(); obj.display(); } }
Static nested class example with instance method:
Java Nested Interface:
syntax of nested interface which is declared within the interface
interface interface_name{ ... interface nested_interface_name{ .... } }
Syntax of nested interface which is declared within the class
class class_name{ ..... interface nested_interface_name{ ..... } ]