Reputation: 3914
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.
Upvotes: 26
Views: 11469
Reputation: 3036
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 a lambda, which should come along the next release 8 of Java SE.
Upvotes: 17
Reputation: 73520
I like to do this kind of thing with a delegate, or "strategy pattern".
public interface ADelegate {
public void method1();
}
public class A {
public A(){....}
public ADelegate delegate;
public final void method1() { delegate.method1(); }
};
A anA = new A();
anA.delegate = new ADelegate() {
public void method1() { ... }
};
Upvotes: 3
Reputation: 31498
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.
Upvotes: 50