Overriding a method in an instantiated Java object

前端 未结 9 1417
陌清茗
陌清茗 2021-02-05 01:55

I would like to override a method in an object that\'s handed to me by a factory that I have little control over.

My specific problem is that I want to override the

9条回答
  •  礼貌的吻别
    2021-02-05 02:18

    I think there is a way to achieve the effect you want. I saw it orriginally used in swing with buttons to allow the programmer to make the button do something when it is clicked.

    Say you have your Foo class:

    public class Foo {
      public Bar doBar() {
        // Some activity
      }
    }
    

    Then you have a runner class or something similar. You can override the doBar() method at the point of instantiation and it will only affect that specific object.

    that class may look like this:

    public class FooInstance{
      Foo F1 = new Foo(){
        public Bar doBar(){
          //new activity
        }
      }
    
      Foo F2 = new Foo();
    
      F1.doBar(); //does the new activity
      F2.doBar(); //does the original activity found in the class
    }
    

    I'm not entirely sure that will do the trick for you but maybe it'll set you in the right direction. If nothing else it is possible to override a method outside of the class, maybe that will help you.

提交回复
热议问题