Wednesday, May 15, 2013

Overriding VS overloading

There is following Java code:
import java.io.*;
class Animal {
    public String sound() {
        return "[no]";
    }
}

class Cat extends Animal {
    public String sound() {
        return "mew";
    }
}

class Dog extends Animal {
    public String sound() {
        return "bow-wow";
    }
}

public class Quiz {
    private static String default_name(Animal a) {
        return "animal";
    }

    private static String default_name(Cat c) {
        return "Shoelace";
    }

    private static String default_name(Dog d) {
        return "Pluto";
    }

    public static void main(String[] args) {
        Animal a = new Dog();

        System.out.println(
            default_name(a) + " says " + a.sound()
        );
    }
}
What and why will be printed?

1 comment:

  1. animal says bow-wow
    default name is just overloaded method, instance of function will be chosen at compile time based on "type of a is Animal" , but sound method of Dog class overrides method of Animal, and right method will be chosen at run time.

    ReplyDelete