Why use method local abstract inner classes

后端 未结 10 1708
名媛妹妹
名媛妹妹 2021-02-05 04:45

One of the legal modifiers you can use with method local inner classes is abstract.

For example:

public class Outer {
    public void method(){
        a         


        
相关标签:
10条回答
  • 2021-02-05 05:22

    IMHO, this feature has NO real use. There's a couple of possible abuses, but there are many other ways to write bad code, you needn't learn this one. :D

    Whenever you try to make use of an abstract method-local class, you need to define at least two concrete method-inner classes. This means you end up with a method containing at least three classes, the method gets quite long and that's quite a bad style.

    You have to know this for the SCJP exam.

    I really hope not. Method-local inner classes are already useless enough to be considered a corner case (you should understand them but probably never use them).

    IMHO, a person asking this in an exam misunderstood Java badly. There can't be accessibility modifiers on a local class since (lacking method literals) the class can't be accessed from the outside anyway. There can be abstract and final modifiers, since there's no reason to forbid them. There are good reasons to allow them: orthogonality and the Principle of least astonishment.

    0 讨论(0)
  • 2021-02-05 05:28

    No, there is no good use for abstract classes (or classes in general) inside methods.

    It would only make sense if only that particular method would need that particular class and would also implement it. Actually having that situation maybe happens once in trillions of methods you write.

    0 讨论(0)
  • 2021-02-05 05:29

    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

    0 讨论(0)
  • 2021-02-05 05:34

    Is there any situation where you would actually use this?

    1. Let S1 denote all situations in which you need an abstract class.

    2. Let S2 denote all situations in which you need a local class.

    3. The answer to your question can be found by examining S1 ∩ S2

    Related questions:

    • What benefit do method-local inner classes provide in Java?
    • Use of Java [Interfaces / Abstract classes]

    Clarification: My point is that the two features (abstract classes and local classes) are two completely orthogonal features of the language. Understanding when each feature is useful is the key to understanding when they are both useful at the same time.

    0 讨论(0)
提交回复
热议问题