Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 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
No answer description is available. Let's discuss.
27 comments Page 1 of 3.

Aaa said:   1 year 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.

Zin said:   8 years ago
It's using the simple concept of Casting. Here two things are happening. We are explicitly up casting foo object t o object class type reference. And in the next one we are trying to downcast object type instance of an object into custom (user-created class foo). Upcasting is automatic. Don't require to upcast any child class to object class.

But downcasting is mandatory. If you avoid explicit downcasting here, you will get an error.

Kripanshu said:   1 decade ago
Object is the super class of all the classes so we can put any instance's reference in the Object reference.

So first reference of new Foo() i.e new object of Foo is given in Object reference o;

Now Object reference o is type cast into Foo stored in foo reference;

Now simply accessed the public data member i of class Foo outside the class using (.) operator.

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

Tanmi said:   6 years ago
Please explain me to get it.

Vishesh said:   7 years ago
Can we make a class in a method?

Bhagya shri said:   9 years ago
In inner class variables can not be public.

Overlord said:   10 years ago
Can we define a class inside the "public static void main" ?

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.

Aniket said:   1 decade ago
Object o=(Object)new Foo();-->Here object of Class Foo is Created and Converted it into Super Class Object.

Foo foo=(Foo)o;-->Here the object is Converted into Subclass i.e. Foo and Assign to reference foo.
And finally the Value of i=3 is displayed by foo.i

Post your comments here:

Your comments will be displayed after verification.