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

Aaa said:   2 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)

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?

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.
(1)

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

Overlord said:   1 decade 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

Sumeet sharma said:   1 decade ago
1. Declaration of new type inside any method is valid.

2. Since new Object of Foo was casted into Object, it's valid.

3. Since Object O contains "Foo" type of object hence casting from object to Foo is valid.

4. At last we are accessing public member of Foo, which is also valid.


Post your comments here:

Your comments will be displayed after verification.