If one class is existing within another class is known as an inner class or nested class
Syntax :
class Outerclass_name
{
............
............
class Innerclass_name1
{
.............
.............
}
class Innerclass_name2
{
...........
...........
}
............
}
The main purpose of using inner class
- To provide more security by making those inner class properties specific to only outer class but not for external classes.
- To make more than one property of classes private properties.
Private is a keyword in java language, it is preceded by any variable that property can be access only within the class but not outside of it (provides more security).
If more than one property of class wants to make as private properties than all can capped under private inner class.
Rules to access properties of inner classes
- Inner class properties can be accessed in the outer class with the object reference but not directly.
- Outer class properties can be access directly within the inner class.
- Inner class properties can't be accessed directly or by creating directly object.
Note: In special situation inner class property can be accessed in the external class by creating special objects with the reference of its outer class.
Program:
class A //outer class { void fun1() { System.out.println("Hello fun1()"); // inner class properties should be access using //object reference in outer class. B ob=new B(); ob.x=10 System.out.println("x= "+ob.x); ob.fun2(); } void fun3() // outer class fun3() { System.out.println("Hello fun3()"); } class B // inner class { int x; // inner class variable void fun2() //inner class fun2() { System.out.println("Hello fun2()"); fun3(); //outer class properties can be access directly } } } class C // external class { void fun3() { System.out.println("Hello fun3()"); } } class IncDemo { public static void main(String args[]) { A oa=new A(); oa.fun1(); C oc=new C(); oc.fun3(); } }Output:
Hello fun1() X=10 Hello fun2() Hello fun3()- Progamming is what actually means ?
- What is software development ?
- How we categorized software development in different manner.
C Plus Plus
Python
Java Development
Web Designing
Javascript
Mysql
Oracle