Search code examples
javasubclasssuperclass

How to call a subclass method from superclass?


Java newbie here.

Banana and Apple extend Fruit (Fruit might as well be an abstract class since no Fruit will ever be instanciated).

Banana and Apple both have a (wildly different) toString() method.

A method somewhere -- let's call it processFruit(Fruit fruit) -- accepts Fruit as a parameter, and then calls the toString() method of the actual Fruit received (meaning, either a banana or an apple), for logging purposes. How do I do this?

I would like to do fruit.toString() and have it run the Apple.toString() or Banana.toString() method based on what the fruit actually is.

Things I'd rather not do (because there are many fruits, not just apples and bananas):

  1. Have two distinct processFruit methods, processFruit(Banana banana) and processFruit(Apple apple), because the code is identical
  2. Downcast the received fruit to either Apple or Banana, and then call its toString() method

There must be another way but I can't see it.


Solution

  • I would like to do fruit.toString() and have it run the Apple.toString() or Banana.toString() method based on what the fruit actually is.

    That's exactly what will happen automatically, so long as you're really overriding the existing parameterless toString() method. That's how method overriding works.

    If you want to do this for a method other than toString() (which is declared in Object) you'd want to create an abstract method in Fruit, and then implement it in each subclass. You can then call it on any Fruit instance, and the right implementation will be called.

    Full example:

    import java.util.*;
    
    abstract class Fruit {
        public abstract String getColor();
    }
    
    class Banana extends Fruit {
        @Override public String getColor() {
            return "yellow";
        }
    }
    
    class Apple extends Fruit {
        @Override public String getColor() {
            return "green";
        }
    }
    
    public class Test {
    
        public static void main(String[] args) {
            List<Fruit> list = new ArrayList<Fruit>();
            list.add(new Banana());
            list.add(new Apple());
    
            for (Fruit fruit : list) {
                System.out.println(fruit.getColor());
            }
        }
    }
    

    See the inheritance part of the Java tutorial for more details.