3

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?

In order to clarify this, suppose I have an interface Database and two implementing classes Database1 and Database2. Database has a method createNode(...) and another one modifyNode(...). The problem is that for Database1 the return type of the createNode method should be a long (the identifier). For Database2, however, it would be an object specific from the technology (in this case OrientDB but this doesn't matter too much, it is simply something that extends Object, of course). And also both create(...) return types should be used as one of modifyNode(...) parameters.

What I was thinking to do is:

`public interface Database {
    public Object createNode(...);
    public void modifyNode(Object id, ...);
    ...
 }`

public class Database1 { 
    @Override
    public Object createNode(...) { 
        ...
        long result = // obtain id of created node
        return Long.valueOf(result);
    }

    @Override
    public void modifyNode(Object id, ...) { 
        ...
        // use id as ((Long)id).longValue();
    }
}

public class Database2 { 
    @Override
    public Object createNode(...) { 
        ...
        SomeObject result = // obtain id of created node
        return result;
    }

    @Override
    public void modifyNode(Object id, ...) { 
        ...
        // use id as (SomeObject)id
    }
}

I wanted to know if there is a better way to do this. Specially to avoid Long -> long and long -> Long conversions. I saw many similar questions here in StackOverflow but none of them were what I was looking for. Thank you very much in advance.

4

2 回答 2

6

这是泛型的示例

数据库

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

数据库1

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
    }
}

数据库2

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
    } 
}

顺便说一句,不用担心自动装箱。您正在使用 JDK >= 5,因为有 @Override 注释。

于 2013-04-21T13:20:08.400 回答
2

我想你想要Generic Methods

泛型方法是引入自己的类型参数的方法。这类似于声明泛型类型,但类型参数的范围仅限于声明它的方法。允许使用静态和非静态泛型方法,以及泛型类构造函数。

泛型方法的语法包括类型参数,位于尖括号内,并出现在方法的返回类型之前。对于静态泛型方法,类型参数部分必须出现在方法的返回类型之前。

于 2013-04-21T13:09:32.033 回答