public class IC1 {
    private int x = 3;
    static int y=4;

    class Inner {
        public void inmet() { System.out.println(x + " " + y);} }

    public void do() {
        Inner i = new Inner();
        i.inmet(); }

    public static void main(String r[]) {
        IC1 ic = new IC1();
        ic.do();
    }
}

Errors

Seems like a pretty straight forward program where in my knowledge I have followed all rules of Inner Class. Checked all {} and ; also. What could be the reason for the errors?

Recommended Answers

"do" is a Java reserved word - just like if, class, while, return etc etc
You can't use a reserved word as an identifier.
You could change it to "doh" - that would seem appropriate :)

Jump to Post

When you define an inner class you can extend an existing class, or implement an interface. The syntax is the same for both, which is simple, but can cause the exact confusion that you have raised.

Jump to Post

you're not really 'instantiating' the interface, you are creating an anonymous class which implements the interface, and that's what you are instantiating.

Jump to Post

All 6 Replies

Re: Inner Class query 80 80

"do" is a Java reserved word - just like if, class, while, return etc etc
You can't use a reserved word as an identifier.
You could change it to "doh" - that would seem appropriate :)

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

Re: Inner Class query 80 80

Oh god! Such silly mistakes will cost me big in the SCJP exam!!! :( Thanks for pointing it out!

Re: Inner Class query 80 80

I have one more doubt regardig Anonymous Class.

    class Sample { 
        void go() {
            Bar b = new Bar();
            b.met(new Foo() {
                public void foof() { System.out.println("foofy");}
                }); 
            } //end go()
        } //end Sample class

    interface Foo { void foof(); }

    class Bar { void met(Foo f) { } }

My doubt is that how can you instantiate an interface (inside the met() arg) when that is strictly not allowed? Or is it an exception case for Anonymous class?

Re: Inner Class query 80 80

When you define an inner class you can extend an existing class, or implement an interface. The syntax is the same for both, which is simple, but can cause the exact confusion that you have raised.

Re: Inner Class query 80 80

you're not really 'instantiating' the interface, you are creating an anonymous class which implements the interface, and that's what you are instantiating.

Re: Inner Class query 80 80

Thanks guys :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.