How are Anonymous inner classes used in Java?

后端 未结 18 1369
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:19

What is the use of anonymous classes in Java? Can we say that usage of anonymous class is one of the advantages of Java?

相关标签:
18条回答
  • 2020-11-21 05:56
    new Thread() {
            public void run() {
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    System.out.println("Exception message: " + e.getMessage());
                    System.out.println("Exception cause: " + e.getCause());
                }
            }
        }.start();
    

    This is also one of the example for anonymous inner type using thread

    0 讨论(0)
  • 2020-11-21 05:59

    i use anonymous objects for calling new Threads..

    new Thread(new Runnable() {
        public void run() {
            // you code
        }
    }).start();
    
    0 讨论(0)
  • 2020-11-21 06:00

    An Anonymous Inner Class is used to create an object that will never be referenced again. It has no name and is declared and created in the same statement. This is used where you would normally use an object's variable. You replace the variable with the new keyword, a call to a constructor and the class definition inside { and }.

    When writing a Threaded Program in Java, it would usually look like this

    ThreadClass task = new ThreadClass();
    Thread runner = new Thread(task);
    runner.start();
    

    The ThreadClass used here would be user defined. This class will implement the Runnable interface which is required for creating threads. In the ThreadClass the run() method (only method in Runnable) needs to be implemented as well. It is clear that getting rid of ThreadClass would be more efficient and that's exactly why Anonymous Inner Classes exist.

    Look at the following code

    Thread runner = new Thread(new Runnable() {
        public void run() {
            //Thread does it's work here
        }
    });
    runner.start();
    

    This code replaces the reference made to task in the top most example. Rather than having a separate class, the Anonymous Inner Class inside the Thread() constructor returns an unnamed object that implements the Runnable interface and overrides the run() method. The method run() would include statements inside that do the work required by the thread.

    Answering the question on whether Anonymous Inner Classes is one of the advantages of Java, I would have to say that I'm not quite sure as I am not familiar with many programming languages at the moment. But what I can say is it is definitely a quicker and easier method of coding.

    References: Sams Teach Yourself Java in 21 Days Seventh Edition

    0 讨论(0)
  • 2020-11-21 06:01

    The best way to optimize code. also, We can use for an overriding method of a class or interface.

    import java.util.Scanner;
    abstract class AnonymousInner {
        abstract void sum();
    }
    
    class AnonymousInnerMain {
        public static void main(String []k){
            Scanner sn = new Scanner(System.in);
            System.out.println("Enter two vlaues");
                int a= Integer.parseInt(sn.nextLine());
                int b= Integer.parseInt(sn.nextLine()); 
            AnonymousInner ac = new AnonymousInner(){
                void sum(){
                    int c= a+b;
                    System.out.println("Sum of two number is: "+c);
                }
            };
            ac.sum();
        }
    
    }
    
    0 讨论(0)
  • 2020-11-21 06:04

    By an "anonymous class", I take it you mean anonymous inner class.

    An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.

    I tend to use it as a shortcut for attaching an event listener:

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            // do something
        }
    });
    

    Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener -- I can just instantiate an anonymous inner class without actually making a separate class.

    I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.

    0 讨论(0)
  • 2020-11-21 06:06

    An inner class is associated with an instance of the outer class and there are two special kinds: Local class and Anonymous class. An anonymous class enables us to declare and instantiate a class at same time, hence makes the code concise. We use them when we need a local class only once as they don't have a name.

    Consider the example from doc where we have a Person class:

    public class Person {
    
        public enum Sex {
            MALE, FEMALE
        }
    
        String name;
        LocalDate birthday;
        Sex gender;
        String emailAddress;
    
        public int getAge() {
            // ...
        }
    
        public void printPerson() {
            // ...
        }
    }
    

    and we have a method to print members that match search criteria as:

    public static void printPersons(
        List<Person> roster, CheckPerson tester) {
        for (Person p : roster) {
            if (tester.test(p)) {
                p.printPerson();
            }
        }
    }
    

    where CheckPerson is an interface like:

    interface CheckPerson {
        boolean test(Person p);
    }
    

    Now we can make use of anonymous class which implements this interface to specify search criteria as:

    printPersons(
        roster,
        new CheckPerson() {
            public boolean test(Person p) {
                return p.getGender() == Person.Sex.MALE
                    && p.getAge() >= 18
                    && p.getAge() <= 25;
            }
        }
    );
    

    Here the interface is very simple and the syntax of anonymous class seems unwieldy and unclear.

    Java 8 has introduced a term Functional Interface which is an interface with only one abstract method, hence we can say CheckPerson is a functional interface. We can make use of Lambda Expression which allows us to pass the function as method argument as:

    printPersons(
                    roster,
                    (Person p) -> p.getGender() == Person.Sex.MALE
                            && p.getAge() >= 18
                            && p.getAge() <= 25
            );
    

    We can use a standard functional interface Predicate in place of the interface CheckPerson, which will further reduce the amount of code required.

    0 讨论(0)
提交回复
热议问题