0
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?

3
Contributors
6
Replies
7
Views
4 Years
Discussion Span
Last Post by rahul.ch
Featured Replies
  • "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 Read More

  • 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. Read More

  • 1

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

0

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

0

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?

Edited by rahul.ch

1

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.

1

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

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.