Welcome Guest | Sign in | Register
Inner Classes - Discussion Page For Q.3018 | Java Programming Questions and Answers | Java Programming Free Online-Tests | LucentBlackBoard | LucentBlackBoard.com

Home > Java Programming > Inner Classes > Questions and Answers

Q: 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.

Answer and Explanation

Answer:57 22

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.

Comment on this Question

Name:

Loading...




Partner Sites
LucentBlackBoard.com                  SoftLucent.com                  LucentJobs.com
All rights reserved © 2012-2015 SoftLucent.