acg
acg

Reputation: 179

Method overriding:Passing derived class object when method accepts base class object

I have above piece of code. As shown below I want to pass derived class as argument to process method.

Please suggest any alternatives.

class Fruit{
}
class Apple extends Fruit{
}

public interface Juice{
public void process(Fruit fruit);
}

Class abstract AbstractFruitManager implements Juice{
}

class FruitManager extends AbstractFruitManager{
public void process(Apple apple){ //gives compilation error...
}
}

Upvotes: 0

Views: 306

Answers (2)

vojta
vojta

Reputation: 5651

You cannot override process method as

public void process(Apple apple)

as you do in your FruitManager class, because it would not be a Juice anymore. Each Juice instance must accept any Fruit in its process method as it was promised in Juice interface.

You have basically three options:

  • rename your process method
  • implement your process method for all Fruits and throw an exception for Strawberries etc.
  • do not implement Juice at all

Upvotes: 1

adrCoder
adrCoder

Reputation: 3275

do it this way

interface Juice {  
    void process(Fruit fruit);
}

and use @Override

class AbstractFruitManager implements Juice{ 
    @Override   
    public void process(Fruit fruit){
    } 
}

Upvotes: 1

Related Questions