Implementing methods from an interface but with different parameters

后端 未结 2 1631
無奈伤痛
無奈伤痛 2020-12-19 21:17

I am looking for a good way to have different implementations of the same method which is defined in an interface but with different parameter types. Would this be possible?

相关标签:
2条回答
  • 2020-12-19 22:08

    Here's an example of Generics

    Database

    public interface Database<T> {
        public T createNode(...);
        public void modifyNode(T id, ...);
        ...  
    }
    

    Database1

    class Database1 implements Database<Long> { 
        @Override
        public Long createNode(...) { 
            ...
            long result = // obtain id of created node
            return result;
        }
    
        @Override
        public void modifyNode(Long id, ...) { 
            ...
            // use id
        }
    }
    

    Database2

    public class Database2 implements Database<SomeObject> { 
        @Override
        public SomeObject createNode(...) { 
            ...
            SomeObject result = // obtain id of created node
            return result;
        }
    
        @Override
        public void modifyNode(SomeObject id, ...) { 
            ...
            // use id as (SomeObject)id
        } 
    }
    

    Btw, don't worry about autoboxing. You are using JDK >= 5 since there are @Override annotations.

    0 讨论(0)
  • 2020-12-19 22:13

    I think you want Generic Methods.

    Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter's scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

    The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.

    0 讨论(0)
提交回复
热议问题