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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.