Site icon TestingDocs.com

Write a java program to calculate the total earnings( Pet Clinic).

Problem Statement

A pet doctor treats dogs, cats and cows in his pet clinic. Write a simple java program to calculate his earnings in the clinic if he treats 25 dogs, 10 cats, 2 cows in a day. Use an objected oriented approach.

Treatment Menu: Fee

Dog          100$

Cat          250$

Cow         1250$

Solution:

Total Pet Doctor Earnings $:7500

Calculation = ( 25 * 100)  + ( 10 * 250 ) + ( 2 * 1250 )

Java Classes

public class PetDoctorEarnings {

    public static void  main(String[] args){
        Dog dog = new Dog(25);
        Cat cat = new Cat(10);
        Cow cow = new Cow(2);
        PetClinic clinic = new PetClinic(3);
        clinic.addAnimal(dog,0);
        clinic.addAnimal(cat,1);
        clinic.addAnimal(cow,2);
        System.out.println("Total Pet Doctor Earnings $:" + clinic.calculateFee());

    }
}

 

Classes used Animal , Dog , Cat and Cow as shown in below picture.

 

Single inheritance

All derived classes have Animal as the super class. We have used single inheritance for the derived classes. Single inheritance is a mechanism that allows a class to only inherit from a single base class.

Dog

public class Dog extends Animal{
    int fee = 100;
    public Dog()
    {
        super();
    }

    public Dog(int number)
    {
        super(number);
    }

    public int getTreatmentFee() {
        return super.getNumber()*100;
    }
}

 

Cat

public class Cat extends Animal {
    int fee = 250;
    public Cat()
    {
        super();
    }

    public Cat( int number)
    {
        super(number);
    }

    public int getTreatmentFee() {
        return  super.getNumber() * fee;
    }
}

 

Cow

public class Cow extends Animal {
    int fee = 1250;
    public Cow()
    {
        super();
    }

    public Cow(int number)
    {
        super(number);
    }

    public int getTreatmentFee() {
        return super.getNumber()*1250;
    }
}

 

Pet Clinic

public class PetClinic {

    private Animal[] animals;

    public PetClinic(int numAnimals) {
        animals = new Animal[numAnimals];
    }

    public void addAnimal(Animal op, int index)
    {
        animals[index] = op;
    }

    public Animal[] getAnimals()
    {
        return animals;
    }

    public int calculateFee()
    {
        int fee = 0;
        for (int i=0; i < animals.length; i++)
            fee += animals[i].getTreatmentFee();

        return fee;
    }
}

 

Further Enhancements

We can make further enhancements to the program. Consider designing an interface contract for the treatable animals.

Let’s name The interface as ITreatable.

public interface ITreatable {
public int getTreatmentFee();
}

Now all treatable animals can implement this interface.

Exit mobile version