Java Programming - Declarations and Access Control - Discussion
Discussion Forum : Declarations and Access Control - General Questions (Q.No. 2)
2.
public class Outer
{
public void someOuterMethod()
{
//Line 5
}
public class Inner { }
public static void main(String[] argv)
{
Outer ot = new Outer();
//Line 10
}
}
Which of the following code fragments inserted, will allow to compile?
Answer: Option
Explanation:
Option A compiles without problem.
Option B gives error - non-static variable cannot be referenced from a static context.
Option C package ot does not exist.
Option D gives error - non-static variable cannot be referenced from a static context.
Discussion:
14 comments Page 1 of 2.
Prakash VL said:
8 years ago
new Inner();
// what I got understand is, object level instance variable can be accessed in the object level method.
In the same way; here they are creating the object of the inner class.
class Test
{
int x;
public void Change()
{
x=10;// This is possible.
Inner in=new Inner();// This is also possible.
}
public class Inner{}
}
// what I got understand is, object level instance variable can be accessed in the object level method.
In the same way; here they are creating the object of the inner class.
class Test
{
int x;
public void Change()
{
x=10;// This is possible.
Inner in=new Inner();// This is also possible.
}
public class Inner{}
}
Alex said:
1 decade ago
simply new Outer(); //At line 5 will also compile
while new ot.Inner(); or new or.Outer(); //At line 5 or 10 will give same error- package ot doesn't exist
while new ot.Inner(); or new or.Outer(); //At line 5 or 10 will give same error- package ot doesn't exist
NIKHIL Patil said:
3 years ago
@All.
If you think, we can add code in line 10 then this was the biggest mistake because method and class both are non-static so it gives always an error.
If you think, we can add code in line 10 then this was the biggest mistake because method and class both are non-static so it gives always an error.
(1)
Bjoooooooo said:
1 decade ago
Instead of
new ot.Inner(); ot.new Inner();
And
Instead of
new Outer.Inner(); new Outer().new Inner();
At line 10.
new ot.Inner(); ot.new Inner();
And
Instead of
new Outer.Inner(); new Outer().new Inner();
At line 10.
Bala said:
10 years ago
There is another error that only one public class is allowed per source code in java.
XYZ said:
9 years ago
The program doesn't compile! But, compiles if the inner class is static.
Ranjitha S said:
8 years ago
What is non-static variable cannot be referenced from a static context?
Alex said:
1 decade ago
new Outer.Inner(); //At line 5 will compile without any error too
Arghyarupa Lenka said:
1 year ago
There can be only one public class in a Java file. Right?
(3)
Shiva said:
1 decade ago
Can we create obj for inner class in outer class?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers