K
K
Ksenia2019-01-30 05:54:18
OOP
Ksenia, 2019-01-30 05:54:18

Is it possible to override a method with new parameters in a descendant class?

Good afternoon!
I'm trying to figure out the intricacies of OOP. A simple example.
There is an abstract class Layer:

public abstract class Layer: ICreatable
{
    float[,] Heights { get; set; }
    public abstract void Create();
}

The interface it implements is also simple:
interface ICreatable
{
    void Create();
}

I want to create a child class that will be a specific type of layer. I don’t understand if it is possible to rewrite the implementation of the Create () method in it as the Create (int someParameter) method? If not, what is the best way to implement my idea. I want every layer type (child class) to be ICreatable.
To be something like this:
public class PerlinNoiseLayer : Layer
{
    private float[,] _heights;

    public override void Create(int resolution)
    {
        ...
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavlo Ponomarenko, 2019-01-30
@Ksushqa

This is contrary to LSP .
Just imagine, you were given such an opportunity and you overridden the method with new parameters. Now we have a method that accepts a Layer or even an ICreatable. Let's say this:

void DoSomething (ICreatable layer) {
  layer.Create();
}

But we can pass a child to this method! We do the following and break our code: Therefore, in this form - no, it is impossible.
To generate each layer, a different set of parameters is needed and they are generated, respectively, in different ways.
Well, you have a difference - so display it in your code.
Is it a layer? - Yes. - Ok, then let's see its height.
If there is such a need - why not introduce a separate interface for heights?
void DoSomething (IHasHeights layer) {
  layer.Heights; // <== тут есть высоты
}

Why not use a factory or builder? Or even make it pass all these parameters to the constructor?
public abstract class Layer: ICreatable
{
    float[,] Heights { get; set; }
    public abstract void Create();
}

public class PerlinNoiseLayer : Layer
{
    private float[,] _heights;
    readonly int _resolution ;

    public PerlinNoiseLayer (int resolution) {
        _resolution = resolution;
    }

    public override void Create()
    {
        // тут расширение уже есть
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question