One of the legal modifiers you can use with method local inner classes is abstract.
For example:
public class Outer { public void method(){ abstract class Inner{ } } }
Is there any situation where you would actually use this?
You have to know this for the SCJP exam.
Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.
Accessing Members: A local inner class has access to fields of the class enclosing it as well as the fields of the block that it is defined within. These classes, however, can access the variables or parameters of the block that encloses it only if they are declared as final or are effectively final.
Why And When To Use Abstract Classes and Methods? To achieve security - hide certain details and only show the important details of an object. Note: Abstraction can also be achieved with Interfaces, which you will learn more about in the next chapter.
One of the legal modifiers you can use with method local inner classes is abstract.
The are some invalid assumptions in the original question. That something is legal/valid Java doesn't mean that it is something that you need to use, or need to know.
I can't recall that the SCJP contains odd corner case questions.
I tried to come up with a case where I would have used an abstract class declared in a method, but everything looks very odd, and reeks of bad design. Here's however a code example that I came up with (still bad code design IMHO)
public class BatchExecutor { public static enum ResultNotification { JMS, MAIL }; public Runnable createRunnable(ResultNotification type) { abstract class Prototype implements Runnable { public void run() { performBusinessLogic(); publishResult(); } abstract void publishResult(); } switch (type) { case JMS: { return new Prototype() { void publishResult() { //Post result to JMS } }; } case MAIL: { return new Prototype() { void publishResult() { //Post result to MAIL } }; } } return null; } private void performBusinessLogic() { //Some business logic } }
I can think only in this case
class Outer { public void method() { abstract class A { void bar(){} abstract void foo(); } class B extends A { @Override void foo() { } } final class C extends A { @Override void foo() { } } A a1 = new B(); A a2 = new C(); } }
But I can't imagine real usage
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