Thinking in Java Fourth Edition Bruce Eckel Chapter 4 Exercise 5

Exercise 5: Create a class called Dog with an overloaded bark( ) method. This method should be overloaded based on various primitive data types, and print different types of barking, howling, etc., depending on which overloaded version is called. Write a main( ) that calls all the different versions. 

class Dog
{
    void bark()
    {
        System.out.println("quiet");
    }
    void bark(char c)
    {
        System.out.println("cawcaw");
    }
    void bark(byte b)
    {
        System.out.println("barkbark");
    }
    void bark(short s)
    {
        System.out.println("slurpslurp");
    }
    void bark(int i)
    {
        System.out.println("iyow");
    }
    void bark(long L)
    {
        System.out.println("lalala");
    }
    void bark(float f)
    {
        System.out.println("fififoofum");
    }
    void bark(double d)
    {
        System.out.println("dodo");
    }
}  


public class DogTalk
{
    public static void main(String[] args)
    {
        Dog d = new Dog();
        char c = 'c';
        byte b = 0;
        short s = 0;
        d.bark();
        d.bark((char)c);
        d.bark((byte)b);
        d.bark((short)s);
        d.bark(1);
        d.bark(1L);
        d.bark(1.0f);
        d.bark(1.0);
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *