Xaad Xadiq Xaad Xadiq - 5 days ago 6
Java Question

How to Avoid Common Repetition of Methods while Inheriting Class/Interfaces?

Suppose I have a class Store which is a super class of 3 classes ( Book , Clothes , Food) , Now I want to add 2 common methods (Description and Price) commonly in all of them and only want to add (calculate tax) method in Food class ....
In Main class

Create array of super reference and then on each reference I have different objects of classes randomly but WHAT I WANT IS THAT I DON'T WANT TO HAVE (calculate tax ) method in Book and clothes , I only want it in Food reference(from array) .

How to achieve this goal by Dynamic Method Dispatch and Interfaces ?

Thanks indeed

Answer

You could write a default method in the Store class. If it is not overridden by the child class it will throw an error only when called.

public interface Store {
    default double calculateTax() {
        throw new UnsupportedOperationException("Operation not defined for this store");
    }
    ...
}

When you define Food you can override this method:

public class Food implements Store {
    @Override
    public double calculateTax() {
        // calculate tax...
    }
    ...
} 

Another alternative would be extending the Store interface to add the extra method

public interface Store { 
    ...
} 

public interface TaxedStore extends {
    double calculateTax();
    ...
}

Now when you define classes like Food you can implement TaxedStore and when you define classes like Book you can implement Store.

Comments