1

I have made these 2 classes to make use of the concept of anonymous inner class. Class 1 has a static inner class. And class 2 uses it. But i cant understand how to call the method of the inner class. Please help me out.

Class 1

public class outerclass {
  outerclass() {
    System.out.println("Constructor of new class");
  }

  public void showthis(String str) {
    System.out.println(str);
  }

  static class insideclass {
    insideclass() {
      System.out.println("This is inside class constructor");
    }

    public void nowshowthis(String str) {
      System.out.println(str);
    }
  }
}

Class 2

public class helloworld {
  public static void main(String args[]) {
    //this is an object of the outer class
    outerclass example=new outerclass();
    //How do i make an anonymous inner class and call the method "nowshowthis()"
  }
}
brimborium
  • 9,362
  • 9
  • 48
  • 76
Sourav301
  • 1,259
  • 1
  • 14
  • 24
  • 4
    Your code doesn't have any anonymous inner classes. All your classes have names. – Jon Skeet Aug 21 '12 at 15:20
  • 2
    I don't think insideclass is anonymous inner class, it is just inner class. – kosa Aug 21 '12 at 15:20
  • 1
    Not directly related to your question, however, [Java naming conventions](http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367) state that class names should begin with capital letters, and the first letter of each internal word capitalized. So `outerclass` should actually be `OuterClass`. – Anthony Grist Aug 21 '12 at 15:22
  • What is more this class is not really static as it is not procced with static keyword. It is good idea to name classes with capital letter. – gregory561 Aug 21 '12 at 15:23
  • Inner class is static , sorry for the mistake. – Sourav301 Aug 21 '12 at 15:26

5 Answers5

3

Let me just get out of my immediate issue! If your inner class in non-static this is how to instanciate it: (assuming example to be an object of type outerclass)

  example.new insideclass().nowshowthis("my String")

For static public inner class, you don't even need an instance of outer class. Just do this (much like accessing public static variable)

new outerclass.insideclass().nowshowthis("my String")

have you tried this?

What's the deal? In your case, you are not really dealing with Anonymous inner class. It's actually just a plain vanilla inner class. (I can't rationalize why would you do that.)

So what's an anonymous class, and where we use it? An anonymous class is like an instance of class for one time use. One of the examples comes to surface when you implement some interface... but you do not need to use it other wise. For example you want to attach a handler to a button. You can do it much like in this fashion (hypothetical example)

   MyButtonInterface obj= new MyButtonInterface(){
      @Override
      onClick(Model obj){
             //save model in DB
       }
   }
   UI.add(obj, "specificId");

you see?

Nishant
  • 54,584
  • 13
  • 112
  • 127
  • Sorry , my mistake , the inner class is static. – Sourav301 Aug 21 '12 at 15:38
  • @Sourav well, I have added all the cases. You see you need to do `new outerclass.insideclass().nowshowthis("my String")` -- but know other stuffs too. (I'm sure you are a good learner) – Nishant Aug 21 '12 at 15:40
3

An anonymous inner class is one that is created AND defined within the body of another class's method. In essence, you are creating a concrete class on the fly from an abstract definition. What you have so far with your InnerClass class is actually just a regular inner class, meaning non-anonymous.

If you want to experiment with anonymous inner classes, the simplest way I can think of is to change your InnerClass to an interface, like so:

public interface InnerClass{
    public void doSomething();
}

So at the moment, InnerClass does squat; it has no meaning until it is defined. Next, you'll want to change how OuterClass works. Change your showThis() function like so:

public showThis(InnerClass innerObj){
    innerObj.doSomething();
}

Now we have your outer class asking the inner class instance to do something, but we still have not defined what it is we want it to do. This is where the magic happens - in your main method, you will define what the inner class instance actually looks like:

public static void main (String[] args){
    OuterClass outer = new OuterClass();

    // This is the key part: Here you are creating a new instance of inner class 
    // AND defining its body. If you are using Eclipse, and only write the 
    // new InnerClass() part, you'll notice that the IDE complains that you need 
    // to implement the doSomething() method, which you will do as though you
    // were creating a plain 'ol class definition
    outer.showThis(new InnerClass(){ 
        public void doSomething(){
            System.out.println("This is the inner anonymous class speaking!");
        }
    });
}

In practice, I've not used anonymous inner classes too much, however they are useful to know about. I have used them most often when I am doing GUI programming, to define listeners for GUI control events, such as a button click.

Also, as other people have mentioned, keep in mind that the Java standard has the first letter of the class name a capital letter, which I have done here. You'll want to follow that standard as it makes it far easier for other people to read your code, and at a glance you can very easily tell when you're looking at a class, and when you're looking at an object.

Anyways, hope that helps.

Paul Richter
  • 10,908
  • 10
  • 52
  • 85
  • Yes this is exactly what i wanted. As you said eclipse complined and so i implemented the doSomething() method . But i am getting one last error on the line outer.showThis(new insideclass() { and the error is - The method showThis(outerclass.insideclass) in the type outerclass is not applicable for the arguments (new insideclass(){}) – Sourav301 Aug 21 '12 at 16:01
  • Oh ok, I forgot that you placed InsideClass inside of the OuterClass class. I guess you could either #1 change the "new InsideClass()" to "new OuterClass.InsideClass()", or #2 move the InsideClass to another file altogether (I would suggest #2, as I can't really think of any major reason to have InsideClass inside of OuterClass). – Paul Richter Aug 21 '12 at 16:09
  • Also, don't forget to accept an answer, whichever one was most helpful to you. – Paul Richter Aug 21 '12 at 16:15
  • Success at last !! Thanks a lot . It worked , so yours is the best answer. And also thanks to all others for their time , i learned a lot. – Sourav301 Aug 21 '12 at 16:19
1

insideclass is an non-static class so it must be accessed via an instance of the outer class as follows:
new outerclass().new insideclass().nowshowthis();

Cratylus
  • 52,998
  • 69
  • 209
  • 339
1

That is not an anonymous inner class. Here is an example of an anonymous inner class:

class InnerClassDemo {
  public static void main(String[] args) {
    ActionListener a = new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println(e.getActionCommand());
      }
    };
    // now a is the only instance of an anonymous inner class implementing the ActionListener interface
  }
}

You can of course also do this with your own interface or class:

class InnerClassDemo {
  public class InsideClass {
      InsideClass() {
          System.out.println("This is inside class constructor");
      }

      public void nowshowthis(String str) {
          System.out.println(str);
      }
  }

  public static void main(String[] args) {
    InsideClass anonym = new InsideClass() {
      @Override
      public void nowshowthis(String str) {
          System.out.println("anonymous inner class override: "+str);
      }
    }
    InsideClass normalInstance = new InsideClass();
    anonym.noshowthis("test");
    normalInstance.noshowthis("test");
  }
}

Your output will be

anonymous inner class override: test
test

So anonym is an instance of an anonymous inner class implementation of InsideClass while normalInstance is just a normal instance of your class InsideClass.

brimborium
  • 9,362
  • 9
  • 48
  • 76
1
public class HelloWorld {

    public static void main(String args[])
        {


        outerclass.insideclass example= new outerclass.insideclass();

        example.nowshowthis("Hello");


    }
}

Or, make the nowshowthis method static and it can be called like so:

outerclass.insideclass.nowshowthis("Howdy. This method is static.");
km1
  • 2,383
  • 1
  • 22
  • 27