📜 ⬆️ ⬇️

The problem was born

I had one idea, which can pleasantly facilitate the programming of some pieces (in a real project).
But whether it will work, I did not know. As a result, I threw a small test to test my guesses.
After writing this test, I discovered that this sample can be quite an interesting and informative java-task.

This is the problem:

 public class A {

     private static A staticInstance;

     public A () {
         staticInstance = this;
     }

     public void f () {
         System.out.println ("Af () called");
     }

     static class B extends A {

         public B () {
             super ();
             throw new RuntimeException ();
         }

         public void f () {
             System.out.println ("Bf () called");
         }
     }

     public static void main (String [] args) {
         try {
             new B ();
         } catch (Throwable t) {
             / * do nothing * /
         }
         if (staticInstance == null) {
             System.out.println ("staticInstance is null");
         } else {
             staticInstance.f ();
         }
     }
 }

The question is - what will be issued to the console after this program is executed?
  1. staticInstance is null
  2. Af () called
  3. Bf () called

')

Source: https://habr.com/ru/post/50102/


All Articles