简体   繁体   中英

Override whole class in java/scala

I have a library, already provided, which has two Scala classes:

class EvaluationFunction (data:DataHolder) {
    def calculate(params:ParamHolder) = {...}
}

And

class Regression {
    def train(data:DataHolder) = {
        ...
        val costFunction = new EvaluationFunction(data)

        //find params to minimize costFunction.calculate(params)
        ....
    }
}

I want to make my own regression class, which behaves exactly like the original regression, but uses a different evaluation function. However, the only way I can think of to do that would involve extending Regression and overwriting the whole train method. But it contains pretty much all the logic in the Regression class - I may as well write it from scratch!

Is there a better way? For example, somehow tell my extended regression class to invoke another class every time the original invokes EvaluationFunction?

The code you show would not compile: the data does not have a datatype.

That aside - the structure of the Regression class is strange. It should have the EvaluationFunction as overridable. As it stands it is built into the train method. That is why you need to override (/rewrite) the entire class. It is a problem with the class structure.

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