JavaRush /Java Blog /Random EN /Level 24. Answers to interview questions on the level top...
zor07
Level 31
Санкт-Петербург

Level 24. Answers to interview questions on the level topic

Published in the Random EN group
Level 24. Answers to interview questions on the topic of level - 1
  1. What do anonymous inner classes compile to?

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

  2. Is it possible to inherit inner classes?

    It is possible to 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 indicate the enclosing external 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 and not the outer one. But when it comes to creating a constructor, the default constructor provided is not suitable and you cannot simply pass a reference to an external object. You must include an expression in the body of the constructor linkНаОбъемлющийКласс.super();. It will provide the missing link and the program will compile.

  3. Is it possible to inherit anonymous inner classes?

    By describing an anonymous class, we are already inheriting from some class or implementing some interface. The words extends or implements cannot be directly applied to anonymous classes, but no one bothers you to prepare in advance and extend the required 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?

    Overriding the inner class as if it were another method of the outer class actually has no effect:

    //: 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 calls the default constructor from the base class. You might think that when creating an object, BigEggan “overridden” class should be used Yolk, but this is by no means the case, as can be seen from the result of the program.

    This example simply shows that when inheriting from an outer class, nothing special happens to inner classes. The two inner classes are completely separate entities, with independent namespaces. In other words, it is impossible.

  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 simple terms - between quotes {}. Most often these quotes are the body of the method. But they can also be just a block, a static block, a body ifof -s, loops, etc.

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

    1. it has access only to the final fields and arguments of the framing method, as well as to all fields of the framing 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 if they have not been changed before the class is initialized. It is also now possible to access non-final parameters of a method.

  6. Can an anonymous inner class contain static methods?

    No. Anonymous inner classes, like internal classes, cannot have static fields or methods. (remember that anonymous classes are compiled into ordinary internal ones, and those, in turn, are associated with the object of the framing class)

  7. Is it possible to create an object of an 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");
            }
       }
    }

    Of course, you InnerClasscannot create an object directly in another class (outside the framing one) in the following way:

    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 internal classes belonging to PrivateConst. The answer is yes, if in some way we manage to obtain an object of the framing class.

  8. Is it possible to declare inner classes private?

    Yes, you can.

    PS Обоснования так и не нашел, но на философии java встречались подобные примеры. Плюс IDE не ругается. Буду признателен за обоснование, но предположу, что в этом плане внутренний класс ничем не отличается от обычного класса.

  9. Можно ли объявлять анонимные внутренние классы private?

    Аналогично (в плане не нашел обоснования). Можно объявить private переменную от типа которой наследуется наш анонимный класс.

  10. Сколько у класса максимально может быть внутренних классов?

    Сколь угодно много. Ограничение особенности ОС и длинны имени файлов.

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