Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force base method call

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..

--edit--

I am mainly curious about overriding methods.

like image 410
irwinb Avatar asked Oct 20 '10 21:10

irwinb


3 Answers

There isn't and shouldn't be anything to do that.

The closest thing I can think of off hand if something like having this in the base class:

public virtual void BeforeFoo(){}

public void Foo()
{

this.BeforeFoo();
//do some stuff
this.AfterFoo();

}

public virtual void AfterFoo(){}

And allow the inheriting class override BeforeFoo and/or AfterFoo

like image 168
MStodd Avatar answered Nov 11 '22 00:11

MStodd


Not in Java. It might be possible in C#, but someone else will have to speak to that.

If I understand correctly you want this:

class A {
    public void foo() {
        // Do superclass stuff
    }
}

class B extends A {
    public void foo() {
        super.foo();
        // Do subclass stuff
    }
}

What you can do in Java to enforce usage of the superclass foo is something like:

class A {
    public final void foo() {
        // Do stuff
        ...
        // Then delegate to subclass
        fooImpl();
    }

    protected abstract void fooImpl();
}

class B extends A {
    protected void fooImpl() {
        // Do subclass stuff
    }
}

It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.

Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.

EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.

like image 11
Cameron Skinner Avatar answered Nov 10 '22 22:11

Cameron Skinner


The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.

This might be useful for scenarios where the method is invoked by some internal API.

i.e. where Foo() is not designed to be invoked directly:

public abstract class ExampleBase {
    private bool _baseInvoked;

    internal protected virtual void Foo() {
        _baseInvoked = true;
        // IMPORTANT: This must always be executed!
    }

    internal void InvokeFoo() {
        Foo();
        if (!_baseInvoked)
            throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
    }
}

Works:

public class ExampleA : ExampleBase {
    protected override void Foo() {
        base.Foo();
    }
}

Yells:

public class ExampleB : ExampleBase {
    protected override void Foo() {
    }
}
like image 5
Lea Hayes Avatar answered Nov 10 '22 22:11

Lea Hayes