jedwards
jedwards

Reputation: 30210

Member shadowing in subclass

Consider the following example outline:

interface IBar{ /*...*/ }

class SomeBar implements IBar { /*...*/ }

abstract class AbstractFoo
{
    IBar context;

    /* Some default implementations of methods manipulating 'context' */
}

class SomeFoo extends AbstractFoo
{
    final SomeBar context = (SomeBar)super.context;       // <-- AAA

    /* Some methods that reference additional non-IBar methods. */

    // The line AAA allows us to use:
    //      context.additionalMethod()
    // instead of
    //      ((SomeBar)context).additionalMethod()
}

My question is about line "AAA". The goal here is to avoid having to cast the context member inherited from the superclass each time it's referenced. In other words, I'd rather

context.additionalMethod()

instead of

((SomeBar)context).additionalMethod()

each time.

This approach seems to work, but I'm wondering if it's correct, or if there is any problem with doing something like this. In my case, this wouldn't lead to ambiguity, although I could see how it could in general.

Also, I just want to make sure that I'm not creating a new object here, but rather having the methods interpret the context reference member differently.

I suppose an alternative would be to rename context to something like rawContext, which might be preferable.

Thanks in advance

Upvotes: 3

Views: 70

Answers (1)

Bohemian
Bohemian

Reputation: 425003

This is a classic case for using generics:

abstract class AbstractFoo<T extends IBar>
{
    protected T context;
    // some default impl
}

Then

class SomeFoo extends AbstractFoo<SomeBar> 
{
    // access context directly as type SomeBar
}

Upvotes: 4

Related Questions