Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.Inner Class in JAVA is a class embedded inside a another Class which is called as outer class. It is also called as Nested Class. Inner class is not accessible from outer class. It is required to create an object of the inner class in outer class.
Advantage:
The inner class can access the methods and variables of the outer class without creating objects of outer class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package org.totalqa.nestedclass; public class OuterClass { public int outerVar = 10; public void displayOuter() { System.out.println("In OuterClass"); } public static void main(String args[]) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); inner.displayInner(); System.out.println(inner.innerVar); } class InnerClass { int innerVar = 20; public void displayInner() { System.out.println("In InnerClass"); System.out.println(outerVar); displayOuter(); } } } |
Static Inner Class in JAVA:
An inner class can be declared as static, in which we can access the inner class from outer class without creating an object of the outer class.
Advantage:
The purpose of the static inner class makes the code more readable and easily under-stable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package org.totalqa.nestedclass; public class StaticInnerClass { public static void main(String[] args) { StaticInnerClass.InnerClass inner = new StaticInnerClass.InnerClass(); System.out.println(inner.innerVar); } static class InnerClass { int innerVar=20; } } |
ById is an static nested inner class in By Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package seleniumexamples; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class InnerStaticClassEx { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); By id = new By.ById("username"); driver.findElement(id).sendKeys("username"); } } |
Conclusion:
static nested inner classes are mainly useful for more readability.
Hi SIr, Could u pls clarify this.
Advantage:
The inner class can access the methods and variables of the outer class without creating objects of outer class.
But OUter class object is created in static area of Outer class main() method.
public static void main(String args[])
{
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.displayInner();
System.out.println(inner.innerVar);
}