Home » Java programming language

How to access inner class in Java?

Java: How to access inner class in java? Here, we are going to learn the concepts of accessing inner class in java? What is the purpose of inner class in java?
Submitted by Preeti Jain, on March 21, 2018

Inner class in Java

We can declare a class within another class such type of class is called inner class.

Syntax:

    class OuterClass{
	    class InnerClass{
	    }
    }

Purpose of inner class in java

Without existing one type of object if there is no chance of existing another type of object then we should go for inner class.

If we want to access inner class methods from static area of outer class then we should first create outer class object (i.e. without existing outer class object then inner class object may not exists) then only after we can access inner class methods.

Example:

class OuterStaticAccess{
	class InnerStaticAccess{
		public void innerAccess(){
			System.out.println("Welcome in inner class");
		}
	}

	public static void main(String[] args){
		OuterStaticAccess o =  new OuterStaticAccess();
		InnerStaticAccess i = o.new InnerStaticAccess();
		i.innerAccess();
	}
}

Output

D:\Java Articles>java OuterStaticAccess
Welcome in inner class

If we want to access inner class methods from instance area of outer class then we also should first create outer class object (i.e. without existing outer class object then inner class object may not exists) then only after we can access inner class methods.

Example:

class OuterInstanceAccess{
	class InnerInstanceAccess{
		public void innerAccess(){
			System.out.println("Welcome in inner class");
		}
	}

	public void outerInstanceAccess(){
		InnerInstanceAccess i = new 	InnerInstanceAccess();
		i.innerAccess();
	}

	public static void main(String[] args){
		OuterInstanceAccess o =  new OuterInstanceAccess();
		o.outerInstanceAccess();
	}
}

Output

D:\Java Articles>java OuterInstanceAccess
Welcome in inner class


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.