Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What will be the output of the program? What will be the output of the program?

ID: 3545190 • Letter: W

Question


What will be the output of the program?


What will be the output of the program?

  public abstract class AbstractTest   {      public int getNum()       {          return 45;      }      public abstract class Bar       {          public int getNum()           {              return 38;          }      }      public static void main (String [] args)       {          AbstractTest t = new AbstractTest()           {              public int getNum()               {                  return 22;              }          };          AbstractTest.Bar f = t.new Bar()           {              public int getNum()               {                  return 57;              }          };                    System.out.println(f.getNum() + " " + t.getNum());      }  }  
A. 57 22 B. 45 38 C. 45 57 D. An exception occurs at runtime.

Explanation / Answer

Option A


Explanation:

You can define an inner class as abstract, which means you can instantiate only concrete subclasses of the abstract inner class. The object referenced by the variable t is an instance of an anonymous subclass of AbstractTest, and the anonymous class overrides the getNum() method to return 22.


The variable referenced by f is an instance of an anonymous subclass of Bar, and the anonymous Bar subclass also overrides the getNum() method (to return 57). Remember that to instantiate a Bar instance, we need an instance of the enclosingAbstractTest class to tie to the new Bar inner class instance. AbstractTestcan't be instantiated because it's abstract, so we created an anonymous subclass (non-abstract) and then used the instance of that anonymous subclass to tie to the new Bar subclass instance.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote