简体   繁体   中英

How to use the anonymous inner class?

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()"
  }
}

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?

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.

insideclass是一个非静态类,因此必须通过外部类的实例进行访问,如下所示:
new outerclass().new insideclass().nowshowthis();

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 .

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.");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM