yellow
yellow

Reputation: 455

To overload a method taking a base class and directing the extending classes method implementation

The logic below is all three classes AppleLeaf, MangoLeaf and BananaLeaf extend Leaf class. I have a method that takes a leaf object only. It should redirect me to the methods below based on the class type correctly. But I get error like, "The method handleLeaf(AppleLeaf) in the type main is not applicable for the arguments (Leaf)"

public void main(String args[]){

      for (Leaf leaf : leafList) {
      handleLeaf(leaf);     
   }
}

private void handleLeaf(AppleLeaf node) {   
    String colour = leaf.getColour();
    System.print.out(colour);
}

private void handleLeaf(MangoLeaf mLeaf) {
     Int veins = mLeaf.getVeinCount;
     System.print.out(veins);
}

 private void handleLeaf(BananaLeaf bLeaf) {    
    Boolean withered = bLeaf.getTexture();
}

Upvotes: 0

Views: 62

Answers (2)

Zircon
Zircon

Reputation: 4707

That's not quite how it works. You've defined three methods, none of which take Leaf as a parameter. Each one takes a subclass of Leaf, but we don't know which subclass of Leaf the given argument might be.

One workaround is to make a delegating method such as:

private void handleLeaf(Leaf leaf) {
    if(leaf instanceof AppleLeaf)
        handleLeaf((AppleLeaf)leaf);
    else if(leaf instanceof MangoLeaf)
        handleLeaf((MangoLeaf)leaf);
    ...//And so on
}

You may consider reworking your logic in general, however. Perhaps you can flip things around to define an abstract method in the Leaf class and have every leaf type handle itself in its own definition of the method.

Upvotes: 1

Koos Gadellaa
Koos Gadellaa

Reputation: 1254

You cannot upcast automatically like that. What you're looking for is dynamic method binding, which is not in Java. Java is a compiletime linked language, and hence, it will not compile/run.

Upvotes: 0

Related Questions