- Class inside a class is known as nested class.
- We will use nested classes to group classes and interfaces at one place for readability and maintainability.
- package com.instanceofjava;
- public class A{
- class B{
- // inner class
- }
- }
- Inner class is a part of nested class. Non-static nested classes are known as inner classes.
- Nested classes are two types
- Non-static nested class(inner class)
- Member inner class
- Anonymous inner class
- Local inner class
- Static nested class.
Member inner class:
- A class is defined within a class and outside of methods of that class known as member inner class.
- package instanceofjavaforus;
- public class A{
- class B{
- public void show(){
- }
- }
- public static void main(String args[]){
- A a= new A();
- a.B b= a.new B();
- b.show();
- }
- }
Anonymous inner class:
- Anonymous inner class is a inner class which does not have a name and whose instance is created at the time creating class itself.
- Anonymous inner classes are somewhat different from normal classes in its creation.
- There are two ways to create in two ways.
- Using class.
- Using interface.
Using class:
- package instanceofjavaforus;
- public class A{
- public void show(){
- }
- public static void main(String args[]){
- A a= new A(){
- public void display(){
- System.out.println('anonymous class method');
- }
- };
- a.display();
- }
- }
Using interface:
- package instanceofjavaforus;
- public interface A{
- public void show();
- }
- package instanceofjavaforus;
- public class Demo{
- public static void main(String args[]){
- A a= new A(){
- public void show(){
- System.out.println('anonymous class method');
- }
- };
- a.show();
- }
- }
Local inner class:
- A class which is defined inside a method of another class known as local inner class
- package instanceofjavaforus;
- public class Demo{
- void create(){
- class A{
- void show(){
- System.out.println("local inner class method");
- }
- }
- A a= new A();
- a.show();
- }
- public static void main(String args[]){
- Demo obj= new Demo();
- obj.create();
- }
- }
Static nested class:
- A static nested class is a class which is defined inside a class as static.
- package instanceofjavaforus;
- public class Outer{
- static class inner{
- public void show(){
- System.out.println("static inner class method");
- }
- }
- public static void main(String args[]){
- Outer.inner in= new Outer.innner();
- in.show();
- }
- }
No comments