Welcome to our comprehensive guide on Java Inner Classes! In this lesson, we'll delve into one of the most powerful features of Java - inner classes. By the end of this tutorial, you'll have a solid understanding of inner classes, their types, and how to use them effectively.
Inner classes are classes declared within another class, interface, or even another inner class. Inner classes have access to the enclosing instance's variables, methods, and constants. This makes them incredibly useful for creating tightly bound classes, improving encapsulation, and organizing code.
Non-Static Inner Classes (Member Inner Classes): These classes can access the instance variables and methods of the enclosing class. They can also be instantiated only within the instance of the outer class.
Static Inner Classes (Static Nested Classes): These classes are declared as static and can access only static variables and methods of the enclosing class. They can be instantiated independently of the outer class.
Let's create a simple example of a non-static inner class. We'll define a Car class with an inner class Engine.
public class Car {
String brand;
Engine engine;
public Car(String brand) {
this.brand = brand;
this.engine = new Engine();
}
public class Engine {
void start() {
System.out.println("Engine started");
}
}
}In this example, we have a Car class with an inner class Engine. When we create a new Car object, an Engine object is also created as part of it. The Engine class can access the instance variables and methods of the Car class.
Now, let's create a simple example of a static inner class. We'll define a Utility class with a static inner class Conversion.
public class Utility {
public static class Conversion {
public static double CelsiusToFahrenheit(double celsius) {
return (celsius * 9 / 5) + 32;
}
}
public static void main(String[] args) {
double celsius = 37.0;
double fahrenheit = Utility.Conversion.CelsiusToFahrenheit(celsius);
System.out.println(celsius + "°C is " + fahrenheit + "°F");
}
}In this example, we have a Utility class with a static inner class Conversion. The Conversion class contains a static method CelsiusToFahrenheit() that can be accessed directly from the Utility class without creating an instance of it.
Inner classes are a powerful feature of Java that allows you to create tightly bound classes, improve encapsulation, and organize your code more effectively. By understanding the different types of inner classes and learning how to create and use them, you'll be well on your way to mastering Java.
What is the purpose of a non-static inner class?
What is the difference between a non-static inner class and a static inner class?