Given:
10. class Line {
11. public class Point { public int x,y;}
12. public Point getPoint() { return new Point(); }
13. }
14. class Triangle {
15. public Triangle() {
16. // insert code here
17. }
18. }
A. Point p = Line.getPoint();
B. Line.Point p = Line.getPoint();
C. Point p = (new Line()).getPoint();
D. Line.Point p = (new Line()).getPoint();
Answer: D
Explanation :
getPoint() method is declared inside Line Class and outside Point class.So in-order to call getPoint() method we must first instantiate Line Class object . Therefore (new Line()).getPoint(); .
The reference variable of inner Point class must be declared in the form OuterClass.InnerClass ,ie Line.Point p ,Since we instantiate inner class Point object in Triangle class constructor .
Output is x and y integer variables of Point object is initialized with Zero and Point Object reference is returned to Triangle Constructor .And the correct Syntax to do so is Option D .
Here are the some other ways to Instantiate Inner class objects outside Outer Class :
new MyOuter().new MyInner(); or outerObjRef.new MyInner();
Nice explaination
ReplyDelete