Home > Software design >  How to call methods in different parent interfaces using child class name?
How to call methods in different parent interfaces using child class name?

Time:08-26

I am migrating a project from python to java. There is a multiple inheritanced python tool class, called Util(TimeUtil, MathUtil, FileUtil, ...), it extend several Util classes. For example

# python
class MathUtil(object):
    @staticmethod
    def add(n, m):
        return n   m


class TimeUtil(object):
    @staticmethod
    def date_to_str():
        return '2022-01-01'


class Util(MathUtil, TimeUtil):
    @staticmethod
    def do_something():
        return

Util.add(1, 2)

Normally, I would call Util.date_to_str(), Util.add(), Util.read_file() in python, importing class Util is enough, and I can call the static method of parent classes by the class name

I want to separate util functions into different util class. Can you show me how to implement calling multiple parent static method with child class name (not instance) in java? If it is not the case, why?

What I have tried

Apparently I can not multiple extend other class in java.

I tried with interface, I put default methods in parent interfaces, and I have to create an instance of the child class to call the methods in parent class. It is not ok because it is a Util class, I want to use class name to call method, not instance of the class

import java.util.Date;

interface MathUtil {

    default int add(int n, int m){
        return n   m;
    }
}

interface TimeUtil{
    default String parseDate(Date date) {
        return "2022-01-01";
    }
}
public class Util implements MathUtil, TimeUtil {

    public static void main(String[] args) {
//        expect code 
//         int add = Util.add(1, 2); 
//         compile error
//         Non-static method 'add(int, int)' cannot be referenced from a static context

        // actual code, it is compiled
        Util util = new Util();
        int add = util.add(1, 2);
    }
}

If I change default method in parent interface to static method, then I have to call the method with parent interface name like MathUtil.add(1, 2), otherwise get compile error: Static method may be invoked on containing interface class only

CodePudding user response:

If you define a static method add() in a MathUtil class, then you call it with MathUtil.add(...).

If you want to call an add() method like Util.add(...), place it into the Util class.

In Java, you have to decide which of the two styles you want. You can't have both.

  • Related