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 3 of 3.

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

Bhagya shri said:   1 decade ago
In inner class variables can not be public.

Zin said:   9 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.
(1)

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

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

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

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)


Post your comments here:

Your comments will be displayed after verification.