I was reading the book "Head First Java" and at some point it mentioned that an inner class instance must be tied to an outer class instance, which I was already aware of, but with an exception:
A very special case—an inner class defined within a static method. But you might go your entire Java life without ever encountering one of these.
I'm pretty sure that last statement is indeed true, but if the compiler allows it to happen it means that it exists for a reason, otherwise it would be illegal Java. Can someone show me an example of where this would be useful?
Inner Classes As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.
Which statement is true about a static nested class? You must have a reference to an instance of the enclosing class in order to instantiate it.
May 25, 2022. An inner class in Java is defined as a class that is declared inside another class. Inner classes are often used to create helper classes, such as views or adapters that are used by the outer class. Inner classes can also be used to create nested data structures, such as a linked list.
It may be special, it may not be.
You're looking at a local class available within a method:
class Foo {
static void bar(){
class MyRunnable implements Runnable {
public void run() {
System.out.println("No longer anonymous!");
}
};
Thread baz = new Thread(new MyRunnable());
}
}
I've seen uses of inner classes that are anonymous like:
class Foo {
static void bar(){
Thread baz=new Thread(new Runnable(){
public void run(){
System.out.println("quux");
}
}
}
}
This is technically an inner class(though anonymous) and defined in a static method. I personally would create a static nested class that implements Runnable and do:
baz = new Thread(new MyRunnable());
where MyRunnable
is defined as:
class Foo {
static void bar(){
// SNIP
}
static class MyRunnable implements Runnable {
public void run() {
System.out.println("No longer anonymous!");
}
}
}
Some people take the view that any method that can be static should be static. To such a person, the inner-beauty of the class would not be terribly relevant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With