Hello guys, Welcome to lingarajtechhub.com . Today we are going to discuss outer class and inner class. Now, let’s see code
Code :
package com.InnerClass.java; public class OuterClass { class InnerClass{ int x = 89; void m1() { System.out.println("Inner Class Method."); } } public static void main(String[] args) { OuterClass ot = new OuterClass(); InnerClass in = ot.new InnerClass(); System.out.println(in.x); in.m1(); } }
Line-1:
- package com.InnerClass.java
It is a java package , this package is created in a java project and it contains classes & interfaces inside the package.
Line-2:
- public class OuterClass
OuterClass is the class name. class is a template used to create objects & class-name first letters must be capital. It is public means we can use this outside of the package.
Line-4:
- class InnerClass
InnerClass is the class name. class is a template used to create objects. Inside the outer class we create the inner class.
Line-5:
- int x = 89
Here x is a variable. int(integer) is a data type of the variable. Here assign x value.
Line-7:
- void m1()
{
System.out.println(“Inner Class Method.”);
}
In this line create a method whose name takes m1().system is a predefined class .Out is a static variable of type printstream present in system class. Println shows the result.
Line-13:
- public static void main(String[] args)
It is a main method in which we can execute a program.
- public : It is an access modifier. The main() is public because we can access main() outside of the class , if main() can’t be public then JVM(Java Virtual Machine) can’t be called main() & code can’t be executed.
- Static : static is a keyword in which the main method has to be static in which JVM can load the class into memory and call the main method without creating an instance.
- Void : Void is a data type. It means no return type.
- main(): Main is a function.
- String [] args : string means collection of characters ,String[] args represents a collection of Strings that are separated by a space and can be typed into the program on the terminal directly.
Line-14:
- OuterClass ot = new OuterClass()
Here “ot” is the instance variable.It is created to assign the default values to the instance variables of the class when an object is created.
Line-15:
- InnerClass in = ot.new InnerClass()
Here “in” is the instance variable.It is created to assign the default values to the instance variables of the class when an object is created.
Line-16:
- System.out.println(in.x)
system is a predefined class .Out is a static variable of type printstream present in system class. Println shows the result.
Line-17:
- in.m1()
“in” is the instance variable of the inner class which is created.”.” is the connector. m1() is the method where the result is stored.
Conclusion:
So in this article, you learn about writing a program using Outer class and Inner class.