简体   繁体   中英

Can I override a new instance of a class object?

I'm not sure what it's called but you can override methods easily with:

Apple foo = new Apple(){
    public void devour(){
        //Devour apple
    }
};

And you can get the Class of an object with getClass.

Is it possible to do something like this:

Apple a = new Apple();
Class<? extends Apple> B = a.getClass();
Apple c = new B(){
    public void polish(){
        //Polish apple
    }
};

Side Note: I'm asking this question because I specifically want to override a single method in the current swing UI class for a component returned by UIManager.getUI(component).getClass() in this code .

In the first code snippet you are creating an anonymous subclass of Apple which overrides the devour() method, and then instantiating foo as an instance of this anonymous subclass.

In the second example, and in your goal, you cannot change the class/type of an object reference after that object already exists .

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