Saturday, March 1, 2014

Suppose I have a class A:
public class A {
    public A(){....}
    public void method1() {...}
};
And an instance of that class:
A anA = new A();
Is there any way to override the method1() only for anA? This question arises when I write a small painting program in which I have to extend the JPanel class several times just to make minor changes to the different panels that have slightly different characteristics.
share|improve this question
 
why not a method2? –  Senthil Kumar Aug 13 '12 at 6:34
add comment

2 Answers

up vote43down voteaccepted
You can do the following:
A anA = new A() {
    public void method1() {
        ...
    }
};
This is the same as:
private static class myA extends A {
    public void method1() {
        ...
    }
}

A anA = new myA();
Only with the exception that in this case myA can be reused. That's not possible with anonymous classes.
share|improve this answer
13 
True, however technically this is creating an anonymous class that extends the class A. –  Stephen C Aug 13 '12 at 6:37
 
@StephenC Indeed. I have updated the answer. Thanks for pointing out. –  jensgram Aug 13 '12 at 6:38
 
@jensgram This might be late but thank you very much. –  Tran Son Hai Mar 16 '13 at 23:25
add comment
You can create a an new anonymous class on the fly, as long as you are using the no-arg constructor of your class A:
A anA = new A() {

  @Override
  public void method1() {
    ...
  }
};
Note that what you want to do is very close to what is known as closure, which should come along with next release 8 of Java SE.

2 comments: