Overriding interface methods on objects you don't instantiate yourself

J

Jacques-Henri

Assume I have a class inherited from JTextComponent. I don't know what type
of Document will be used as its model, however I want to add functionnality
in the insertString() method of this Document instance.

How do I do this?

If that's not clear, I'd like to do something like this:

public class MyTextComponent extends JTextComponent {
...
protected Document createDefaultModel() {
return super.createDefaultModel() { // doesn't work, ofc

public void insertString(int offset, String str, AttributeSet a)
{
doSomething();
super.insertString(offset, str, a);
}

};

}

}
 
M

Michael Borgwardt

Jacques-Henri said:
Assume I have a class inherited from JTextComponent. I don't know what type
of Document will be used as its model, however I want to add functionnality
in the insertString() method of this Document instance.

How do I do this?

If that's not clear, I'd like to do something like this:

public class MyTextComponent extends JTextComponent {
...
protected Document createDefaultModel() {
return super.createDefaultModel() { // doesn't work, ofc

No, it can indeed not be done that way. Instead you (have to) use the
Decorator pattern, i.e. write a "wrapper" class that takes the object in
question and forwards all calls to it, modifying those you need modified.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top