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);
    }
}
i = 3
Compilation fails.
i = 5
A ClassCastException will occur.
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
27 comments Page 2 of 3.

Ranjeet Kumar Sahu said:   1 decade ago
As we know Object class is the super class of the class hierarchy so the reference of Object class can refer to any of its sub class.

Again we are converting the Object reference to the foo object by typecasting that is possible.

Anshika said:   1 decade ago
Object o=(Object)new Foo();this syntax is written to confuse programmers and check the basics. object is the superclass of all clsses in java.and type casting is done after instantiating an object of class object.

Aaa said:   3 years ago
How can we have a non-static reference (inner class is non-static) in a static context (main function is static). Isn’t it wrong?

Please explain me.
(1)

Vinod said:   1 decade ago
We can access the class member within the class with object reference or we can access with class reference means with class name also.

Oshin said:   1 decade ago
Some time when we typecast superclass object into sub class it will throw a classCastException. When that Exception aries?

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.

Hari said:   1 decade ago
This is an example of inner class. To instantiate an inner class, we have to Instantiate outer class first.

Kavita jalalli said:   1 decade ago
Object o = (Object)new Foo();
Foo foo = (Foo)o;

It is equal to
Foo foo=new Foo();

Prinks said:   1 decade ago
object is the super class of all the classes.... so kind of type casting is done....

Kalyan said:   6 years ago
Can we use nested class in this. I can't understand how it is.


Post your comments here:

Your comments will be displayed after verification.