简体   繁体   中英

How to ensure that at least one of two methods in Java class is overridden?

I have a base Java class, which has two similar methods:

class Base {
    public void processA(SomeClass sc, Args args);
    public void processB(AnotherClass ac, Args argc);
}

I would like to create a descendant, which must implement at least one of these two methods of the Base class. For instance, I consider following variants are correct ( "good" ):

class ChildA extends Base {
    public void processA(SomeClass sc, Args args);
}

class ChildB extends Base {
    public void processB(AnotherClass ac, Args args);
}

But the following variant is wrong (let's call it "bad" ):

class ChildC extends Base {
    /* nothing here */
}

So the question is how methods process{A,B} must be implemented/designated to allow detection of such "bad" and "good" implementation of the childs at compile time?

Now I'm using run-time detection like this:

class Base {
    public void processA(SomeClass sc, Args args) {
        throw new NullPointerException("Hey, buddy, you forget to implement this, but calling it.");
    }
    public void processB(AnotherClass ac, Args argc) {
        throw new NullPointerException("Hey, buddy, you forget to implement this, but calling it.");
    }
}

Maybe there is another good approach to do this?

You can't do this cause it defeats polymorphism . Since you don't provide an implementation for your methods ,your Base should be either abstract or an interface .

In your example both methods must be overriden.

My approach is to change your design. Since the only thing I can see similar to your methods is the signature.

uml设计

First make a concrete class implementing the process method, therefore having your Base class loose coupled you can pass different classes.

You can also extend you paradigm using decorator design pattern if you want to have multiple processes.

A simpler approach is to make an empty implementation.

Declare your methods abstract . Any class that extends a class with abstract methods must implement them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM