Adding functions to Java class libraries

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2010-05-03T21:01:17Z Indexed on 2010/05/03 21:08 UTC
Read the original article Hit count: 169

Filed under:
|
|
|

I'm using a Java class library that is in many ways incomplete: there are many classes that I feel ought to have additional member functions built in. However, I am unsure of the best practice of adding these member functions.

Lets call the insufficient base class A.

class A
{
    public A(/*long arbitrary arguments*/)
    {
        //...
    }

    public A(/*long even more arbitrary arguments*/)
    {
        //...
    }

    public int func()
    {
        return 1;
    }
}

Ideally, I would like to add a function to A. However, I can't do that. My choice is between:

class B extends A
{
    //Implement ALL of A's constructors here

    public int reallyUsefulFunction()
    {
        return func()+1;
    }
}

and

class AddedFuncs
{
    public int reallyUsefulFunction(A a)
    {
        return a.func()+1;
    }
}

The way I see it, they both have advantages and disadvantages. The first choice gives a cleaner syntax than the second, and is more logical, but has problems: Let's say I have a third class, C, within the class library.

class C
{
    public A func()
    {
        return new A(/*...*/);
    }
}

As I see it, there is no easy way of doing this:

C c;
int useful = c.func().reallyUsefulFunction();

as the type returned by C.func() is an A, not a B, and you can't down-cast.

So what is the best way of adding a member function to a read-only library class?

© Stack Overflow or respective owner

Related posts about java

Related posts about classes