简体   繁体   中英

Add new method to existing class

I know about anonymous class.We can use it to override class methods.This is an example:

public class User {
    private final  String name;
    public User(final String name){
        this.name=name;
    }
    public void sayHello(){
        System.out.println("Hello : "+name);
    }
    public static void main(String[] args) {
        User s = new User("CHORT"){
        @Override
        public void sayHello(){
            System.out.println("HELLO FROM ANONYMOUS CLASS");
        }
    };

    }
}

But i noticed that the following contruction is also correct(Not highlighted by my IDEA)

public class User {
    private final  String name;
    public User(final String name){
        this.name=name;
    }
    public void sayHello(){
        System.out.println("Hello : "+name);
    }
    public static void main(String[] args) {
        User s = new User("CHORT"){

        public void sayHello2(){
            System.out.println("HELLO FROM ANONYMOUS CLASS");
        }
    };

    }
}

But when i want to call method sayHello2, IDEA show me that it doesn't exist.What is the purpose of this contruction?

First of all, the title of the question is wrong. You did not "Add new method to existing class". You added a method to an anonymous class that extends an existing class.

Anonymous classes can contain any methods that regular classes do. They don't have to only contain methods of the class they extend or the interface they implement.

Therefore, defining sayHello2 in your anonymous class is perfectly valid, but quite useless, since you can't call that method from outside the anonymous class body.

On the other hand, it can be useful if you do call it from within the anonymous class body (and you can make it private , since it can't be called from outside anyway):

User s = new User("CHORT") {
    @Override
    public void sayHello() {
        sayHello2();
    }
    private void sayHello2() {
        System.out.println("HELLO FROM ANONYMOUS CLASS");
    }
};

EDIT: Another thing I thought about - you can probably use reflection to call your sayHello2 from outside, though I'm not sure why you'd ever want to do that.

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