zor07
Level 31
Санкт-Петербург

Level 24

Published in the Random EN group
Level 24
  1. What are anonymous inner classes compiled into?

    Anonymous inner classes are compiled into внешнийКласс$n.class. In place of the outer class, respectively, the name of the framing class, inside which the anonymous inner class is described. In place of n is a number from 1 to the number of anonymous classes.

  2. Is it possible to inherit inner classes?

    You can inherit inner classes from others.

    Inheritance from an inner class is a little more complicated than usual, since the constructor of the inner class is associated with a reference to the surrounding outer object. The problem is that the "hidden" object reference of the enclosing outer class must be initialized, and there is no longer a default enclosing object in the derived class. To explicitly specify an enclosing outer object, a special syntax is used:

    //: innerclasses/InheritInner.java
    // Наследование от внутреннего класса.
    
    class WithInner {
      class Inner {}
    }
    
    public class InheritInner extends WithInner.Inner {
      //! InheritInner() {} // He компorруется
      InheritInner(WithInner wi) {
        wi.super();
      }
      public static void main(String[] args) {
        WithInner wi = new WithInner();
        InheritInner ii = new InheritInner(wi);
      }
    }

    Here the class InheritInneronly extends the inner class, not the outer one. But when it comes to creating a constructor, the default constructor doesn't work, and you can't just pass a reference to an external object. You must include an expression in the body of the constructor linkНаОбъемлющийКласс.super();in the body of the constructor. It will provide the missing reference and the program will compile.

  3. Is it possible to inherit anonymous inner classes?

    Describing an anonymous class, we are already inheriting from some class or implementing some interface. You cannot directly apply the words extends or implements to anonymous classes, but no one bothers to prepare in advance and extend the desired interface, which we will implement using an anonymous class. An example in the code below.

    import java.awt.event.WindowListener;
    
    public class TestExtendAnonym {
        private interface MyInterface extends Runnable, WindowListener {
        }
    
        Runnable r = new MyInterface() {
        ...
        //Пример того How реализовать 2 и более интерфейса в анонимном классе
        };
    }

    You cannot inherit from an anonymous class.

  4. Is it possible to override inner classes?

    Redefining the inner class as if it were another method of the outer class has no effect in fact:

    //: innerclasses/BigEgg.java
    // Внутренний класс нельзя переопределить
    // подобно обычному методу,
    import static net.mindview.util.Print.*;
    
    class Egg {
      private Yolk y;
      protected class Yolk {
        public Yolk() { print("Egg.Yolk()"); }
      }
      public Egg() {
        print("New Egg()");
        y = new Yolk();
      }
    }
    
    public class BigEgg extends Egg {
      public class Yolk {
        public Yolk() { print("BigEgg.Yolk()"); }
      }
      public static void main(String[] args) {
        new BigEgg();
      }
    }

    Conclusion:

    New Egg()
    Egg.Yolk()

    The default constructor is automatically synthesized by the compiler and the default constructor from the base class is called in it. You might think that BigEggan "overridden" class should be used when creating an object Yolk, but this is by no means the case, as can be seen from the output of the program.

    This example just shows that when you inherit from an outer class, nothing special happens to inner classes. The two inner classes are completely separate entities, with independent namespaces. In other words, you can't.

  5. What are the limitations of local classes?

    First, let's remember what a local class is. This is a class described in a block of code, that is, in a simple way - between quotes {}. Most often, these quotes are the method body. But they can also be just a block, a static block, the body ifof -s, loops, and so on.

    The local class is endowed with the features of inner classes, but has distinctive features, namely:

    1. it has access only to the final fields and arguments of the wrapping method, as well as to all fields of the wrapping class, including private and static ones;
    2. a local class is visible and can only be created in the block in which it is described;
    3. the local class does not have an access modifier;
    4. cannot have static fields, methods, classes (except for final ones);
    5. a local class declared in a static block can only access static fields of the outer class.

    But! Since Java8, we can access non-final local variables in local classes, as long as they haven't been changed before the class was initialized. It is also now possible to access non-final method parameters.

  6. Can an anonymous inner class contain static methods?

    No. Anonymous inner classes, like inner classes, cannot have static fields or methods. (remember that anonymous classes are compiled into regular inner classes, which in turn are associated with the object of the enclosing class)

  7. Is it possible to create an object of the inner class if the outer class only has privatea constructor?

    Having code like this:

    public class PrivateConst {
        private PrivateConst() {}
        public class InnerClass{
            public void f(){
                System.out.println("hello");
            }
       }
    }

    Directly, in another class (outside the framing class), of course, creating an object InnerClassin the following way will not work:

    PrivateConst.InnerClass priv = new PrivateConst().new InnerClass();

    But! What if we have a method that returns an instance

    PrivateConst:public class PrivateConst {
        private static PrivateConst instance;
        private PrivateConst() {}
    
        public static PrivateConst getInstance(){
            instance = new PrivateConst();
            return instance;
        }
    
        public class InnerClass{}
    }

    In this case, the private constructor does not prevent us from creating an object InnerClass. We can also easily create it in methods and in other inner classes belonging to PrivateConst. The answer is yes, if by some means we manage to get an object of the framing class.

  8. Is it possible to declare inner classes private?

    Yes, you can.

    PS I did not find a justification, but there were similar examples in the philosophy of java. Plus IDE does not swear. I would appreciate the rationale, but I will assume that in this respect the inner class is no different from the normal class.

  9. Is it possible to declare anonymous inner classes private?

    Similarly (in the plan did not find justification). You can declare privatea variable from the type of which our anonymous class inherits.

  10. How many inner classes can a class have?

    As much as you like. Restriction features of the OS and the length of the file name.

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION