Java Programming - Inner Classes - Discussion
Discussion Forum : Inner Classes - Finding the output (Q.No. 1)
1.
What will be the output of the program?
public class Foo
{
Foo()
{
System.out.print("foo");
}
class Bar
{
Bar()
{
System.out.print("bar");
}
public void go()
{
System.out.print("hi");
}
} /* class Bar ends */
public static void main (String [] args)
{
Foo f = new Foo();
f.makeBar();
}
void makeBar()
{
(new Bar() {}).go();
}
}/* class Foo ends */
Answer: Option
Explanation:
Option C is correct because first the Foo instance is created, which means the Foo constructor runs and prints "foo". Next, the makeBar() method is invoked which creates a Bar, which means the Bar constructor runs and prints "bar", and finally the go() method is invoked on the new Bar instance, which means the go() method prints "hi".
Discussion:
15 comments Page 2 of 2.
Sumanth said:
9 years ago
foo f = new foo();
f.makeBar();
=========
(new Bar() {}).go();
Look at these statements closely.
Step 1:
foo f = new foo(); its Foo class constructor will be initiated first .. so "foo" will be printed (since it is system.out.print ) foo will be printed output. The output continues to print the same line
Step 2: (new Bar() {}).go(); statement.. printS barhi.., So all together output will be foobarhi.
Please correct me if I am wrong.
f.makeBar();
=========
(new Bar() {}).go();
Look at these statements closely.
Step 1:
foo f = new foo(); its Foo class constructor will be initiated first .. so "foo" will be printed (since it is system.out.print ) foo will be printed output. The output continues to print the same line
Step 2: (new Bar() {}).go(); statement.. printS barhi.., So all together output will be foobarhi.
Please correct me if I am wrong.
Vasavisreenivas said:
8 years ago
Actually, the compilation of the program do occur because the void makebar() method has to be placed in the Foo file we will get that given output as foobarhi.
SAYYED NURJAHAN said:
5 years ago
Can you please tell me, What is the difference between system.out.println and system.out.print?
Deepak said:
5 years ago
@Sayyed Nurjahan.
system.out.println()->>> will print the output and move the next line.
system.out.print()->>>>>will print the output and be in the same line.
system.out.println()->>> will print the output and move the next line.
system.out.print()->>>>>will print the output and be in the same line.
Nikhil said:
4 years ago
If you remove {} even that code will run, and that is the Anonymous class.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers