Java Programming - Declarations and Access Control - Discussion
Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 2)
2.
What will be the output of the program?
public class Test
{
public static void main(String args[])
{
class Foo
{
public int i = 3;
}
Object o = (Object)new Foo();
Foo foo = (Foo)o;
System.out.println("i = " + foo.i);
}
}
Discussion:
27 comments Page 3 of 3.
Alok gupta said:
1 decade ago
In this answer i=3 is right.
Because in the casting manner object can be cast.
And I variable access by the object.
Because in the casting manner object can be cast.
And I variable access by the object.
Mukta said:
1 decade ago
It will work when simply written
Foo foo = new Foo();
also.
no need to write any other statement except this.
but in Question Object class is used.which is superclass of all classes direct or indirect in java including your class also.so in other words father of all classes.so it can store any reference of any object.
here its the same
Object o = (Object)new Foo();
once the Foo object reference is stored in o ref variable.it is then typecasted in Foo class type.this is needed because we want to access int i variable of foo class.we can not call it directly by using o reference.it will give error cannot find symbol.
Foo foo = new Foo();
also.
no need to write any other statement except this.
but in Question Object class is used.which is superclass of all classes direct or indirect in java including your class also.so in other words father of all classes.so it can store any reference of any object.
here its the same
Object o = (Object)new Foo();
once the Foo object reference is stored in o ref variable.it is then typecasted in Foo class type.this is needed because we want to access int i variable of foo class.we can not call it directly by using o reference.it will give error cannot find symbol.
Susant said:
1 decade ago
Because of type cast.
Utkarsh said:
1 decade ago
There is nothing more than Type Cast...
Prinks said:
1 decade ago
object is the super class of all the classes.... so kind of type casting is done....
Gurwinder Singh said:
1 decade ago
Here dmd technique is used and no need of casting it. Again that reference address is copied to same inner class reference. That completed the consturction of inner class. So it gave the outpur i=3;.
Note: When reference of Object class is copied to inner class. Type casting is required.
Note: When reference of Object class is copied to inner class. Type casting is required.
Saranya said:
2 decades ago
I need a description for this answer.
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers