Extending factory-made class

A library, for instance JDK core APIs, usually offers instances of internal concrete class. For users

of the library, the class is usually given as an abstract class. Some of them may or may not have static factory method that delivers a concrete class instance. For example, FileSystemView has

and Graphics hasn't. The difference is not important for the problem of this thread.

We can get those concrete class by calling Object#getClass() method. But how could we extend

the class and override just one or two methods for trivial, but important, customization? In other

words, we'd like to use a major part of the implementation as is, not implementing the abstract

class from scratch.

[733 byte] By [hiwaa] at [2007-10-2 11:24:39]
# 1
You can't do that - The Factory will never return an instance of your class.What you can do, if it is not necessary that the factory returns your class, you can use a Delegate which wrapps the concrete class returned by the factory.
andiha at 2007-7-13 4:29:54 > top of Java-index,Java Essentials,Java Programming...
# 2

Extending an unkown class is hardly what you want to do. What if the class of the object you get from somewhere is not accessible? It could be private, it could be a local inner class, it could even be final. I think what you want to do is create a "proxy class" that extends the abstract class and delegates most of the method calls to the instance you have got.

If you only needed to implement interfaces you could use the Proxy class in java.lang.reflect to create such objects, but with abstract classes it's not that easy.

jsalonena at 2007-7-13 4:29:54 > top of Java-index,Java Essentials,Java Programming...
# 3

> We can get those concrete class by calling

> Object#getClass() method. But how could we extend

> the class and override just one or two methods for

> trivial, but important, customization? In other

> words, we'd like to use a major part of the

> implementation as is, not implementing the abstract

> class from scratch.

I'm not sure I fully understand what you want to do but I think you could use the idea behind the Adapter pattern. You create an adapter class with the public interface you want and then you use an object of the class you want to customize (the adptee) to implement that adapter class.

Most adapter class methods will just call the corresponding methods of the adaptee but some are implemented differently.

jsalonena at 2007-7-13 4:29:54 > top of Java-index,Java Essentials,Java Programming...
# 4
Thanks a, j and sixdots for excellent ideas.I will try implementing the wrapper, or a Delegate or an Adapter, and will post the results.
hiwaa at 2007-7-13 4:29:54 > top of Java-index,Java Essentials,Java Programming...