How to create generic interface methods? - java

is it possible to create a generic method in interfaces?
say I want to create an interface
public interface Merge {
public void merge(Object host, Object other);
}
then I want the implementing class to implement this, but define the type of host and other.
e.g.
public class FooBazMerge implements Merge {
public void merge(Foo host, Baz other){
// merge some properties
}
}
the reason why I want to do this is so that I can do something like this
public class SomeObject {
private Merge merge;
private Foo foo;
private Baz baz;
public setMerge(Merge merge){
this.merge = merge
}
public void merge(SomeObject anotherObject){
merge.merge(this.foo, anotherObject.getBaz());
}
}
I basically want to delegate the merging responsibility/logic of someObject to FooBazMerge. that way I can change the implementation of how it's merged without having to muck with the domain models every time an adjustment needs to be made.

public interface Merge<A,B> {
public void merge(A host, B other);
}
is this what you are looking for? This is valid syntax. Your implementing class would look like:
public class FooBazMerge implements Merge<Foo, Baz> {
public void merge(Foo host, Baz other){
// merge some properties
}
}

It seems like you want something like...
public interface Merge<T,S> {
public void merge(T host, S other);
}

Check out this page for nice examples of generic interface implementation.
This should help of how to implement one.
http://www.java2s.com/Code/Java/Language-Basics/Agenericinterfaceexample.htm

Related

How to use an interface as parameter of other interface with multiple implementations?

I am trying to fix this.
There is a public interface StudentValidation that has this method:
default public void validateStudent(ObjectA inputA){};
default public void validateStudent(ObjectB inputB, ObjectC inputC){};
and it has implementations in two different classes.
So I have
ValidatorStudentSchoolBased that process the value for validateStudent(ObjectA inputA)...
and
ValidateStudentsHomeBased that process validateStudent(ObjectB inputB, ObjectC inputC)
So right now the common interface makes not so much sense and I was wondering if there is any strategy, interface/implementation that I could use for this case so I could be able to send one just parameter like
default public void validateStudent(MyObject myObject)
So far I created MyObject -> StudentClass as an empty interface What is an Empty interface used for and with two specific implementation that are according the needs
So I did this
public interface StudentClass {}
and then
public class StudentClassSchoolBased implements StudentClass () {
ObjectA inputA;
//getters and setters
}
I will also create the implementation StudentHomeBased
Then edited StudentValidation like
validateStudent(StudentClass myObject)
And change the implementations like:
ValidatorStudentSchoolBased(StudentClassHomeBased myObject)
Says does not match the interface (and I cannot override) due the type of the interface is StudentClass and even if StudentClassHomeBased implements it, does not the trick, any idea of how to do what I am trying to do?
Basically, what I want to do is this
create an interface method that as parameter receives another interface with multiple implementations, is that possible?
I think your case can be resolved by using generics and parametrizing StudentValidation.
Is this what you are trying to achieve?
public interface StudentValidation<T>{
public void validateStudent(T student);
}
public class ValidatorStudentSchoolBased implements
StudentValidation<StudentClassSchoolBased>{
#Override
public void validateStudent(StudentClassSchoolBased student) {
}
}
public class ValidateStudentsHomeBased implements
StudentValidation<StudentClassHomeBased>{
#Override
public void validateStudent(StudentClassHomeBased student) {
}
}

Partial implementation of interface

I have an Inreface say
public interface myInterfacy {
String kilogramToGram();
Long litresTomiliLitres();
String inchesToMillimeters();
String ouncesToGrams();
}
I need to have multiple implementaton of this interface but I want the partial implementation of this inteface on different implementation,
As:
public class A implements myInterfacy {
public String kilogramToGram(){
//code
};
I don't want to give the definition of other methods.
}
public class B implements myInterfacy {
Long litresTomiliLitres(){
//code
};
I don't want to give the definition of other methods.
}
I thought that I can di it via using an abstract class, but I wonder If any other good approach is possible.
The answer is relatively simple but has many options.
You could
Make a number of partial interfaces and the one that "does it all" implements them all (not great)
You could make a number of "dummy" interfaces which throw an exception of unimplemented functionality. So, every proxy class would implement the full interface but throw runtime errors on unsupported methods (also not great)
Simply do nothing - literally. Implement the full interface and provide empty bodies (also really not great)
Or, you could encapsulate the functionality with a specific proxy to provide the given functionality.For example,
class FullyFunctional {
public void foo() {...}
public void bar() {...}
}
class PartiallyFunctional {
FullyFunctional ff;
public PartiallyFunctional(FullyFunctional ff) {
this.ff = ff;
}
// No foo...
public void bar() { ff.bar(); }
}
One way to do this, is with a convenience base class. This is however not really a good idea, because you won't get compile type checking to help ensure that you don't call unimplemented method.
public interface Converter {
public String kilogramToGram();
public long litresTomiliLitres();
public String inchesToMillimeters();
public String ouncesToGrams();
}
public abstract class AbstractConverter implements Converter {
#Override
public String kilogramToGram() {
throw new UnsupportedOperationException();
}
#Override
public long litresTomiliLitres() {
throw new UnsupportedOperationException();
}
#Override
public String inchesToMillimeters() {
throw new UnsupportedOperationException();
}
#Override
public String ouncesToGrams() {
throw new UnsupportedOperationException();
}
}
public final class A extends AbstractConverter {
#Override
public String kilogramToGram() {
//code
}
}
Follow interface-segregation-principle
Divide fat interface into granular small interfaces
Implement only require interface
One extreme case: I will declare four interfaces for four methods
public interface IKGToGram {
String kilogramToGram();
}
public interface ILitersToMilliLeters{
Long litresTomiliLitres();
}
public interface IInchesToMilliMeters{
String inchesToMillimeters();
}
public interface IOunceToGrams{
String ouncesToGrams();
}
Now you can implement whatever interface set you want to.
Have a look at explanation about interface segregation concept:
Interface Segregation Principle- Program to an interface

Java Method with generic class as argument

It is possible write a method in java with generic class with argumet??
example:
public void Transfer (class c){
class.Search();
}
Yes, you would need to do something like so:
public class Foo<T> {
public void Transfer(T c) {
c.Search();
}
}
Since you seem to want to invoke a specific method, you might want to define an interface which provides the methods you are after, and bind the generic constraint with it:
public interface MyInt {
void Search();
}
....
public class Foo<T extends MyInt> {
public void Transfer(T c) {
c.Search();
}
}
Alternatively:
public class Foo {
public void Transfer(MyInt c) {
c.Search();
}
}
The last example does away with generics and uses interfaces, which can sometimes yield code which is easier to follow, depending on what you are trying to achieve.

How to override a method or assign a parameter value of a library class?

I'm developing a java application using a certain library(included using a jar file), i want to override a method exists on a class(abstract class) contained in that library, or even change a certain parameter value in it.
Is there is a way to do that?
Extend the class from which you want to override the method.
public class ClassFromExtLib {
public void foo(Object param) {
}
}
public class MyClass extends ClassFromExtLib {
#Override
public void foo(Object param) {
super.foo(param);
//adding my own implementation...
}
}
If you can't extend the class, use a wrapper class that can execute the method and then add your own logic to it.
public final class ClassFromExtLib {
public void foo(Object param) {
}
}
public class MyClass {
//code to initialize the instance of the class ommited
private ClassFromExtLib bar;
public void foo(Object param) {
bar.foo(param);
//adding my own implementation...
}
public void foo(Object param, Object param2) {
bar.foo(param);
//adding my own implementation using param and param2...
}
}
If you want to add/remove parameters from the method, then you can't do this by an overriding, that's an overloading. The second way would be the best for you.
Yes and no. You can create a subclass which has the different behavior you want.
public class MyVersion extends JarVersion {
However if you change the signature, callers will typically ignore the change.
You can also use the delegate pattern.
public MyClass {
JarClass delegate;
public void myMethod(MyParm mp) {
JarParm jp = makeJPfromMP(mp);
extraStuff();
delegate.originalMethod(jp);
moreExtraStuff();
}
Its very simple,
Just create one another class that extends that class(assuming its extendable) for which you need modification
And then override the methods that you want to change.

Extending functionality of all implementations of an Interface?

I'm looking to create a set of functions which all implementations of a certain Interface can be extended to use. My question is whether there's a way to do this without using a proxy or manually extending each implementation of the interface?
My initial idea was to see if it was possible to use generics; using a parameterized type as the super type of my implementation...
public class NewFunctionality<T extends OldFunctionality> extends T {
//...
}
...but this is illegal. I don't exactly know why this is illegal, but it does sort of feel right that it is (probably because T could itself be an interface rather than an implementation).
Are there any other ways to achieve what I'm trying to do?
EDIT One example of something I might want to do is to extend java.util.List... Using my dodgy, illegal syntax:
public class FilterByType<T extends List> extends T {
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
}
You can achieve something like this using a programming pattern known as a 'decorator' (although if the interface is large then unfortunately this is a bit verbose to implement in Java because you need to write single-line implementations of every method in the interface):
public class FilterByType<T> implements List<T> {
private List<T> _list;
public FilterByType(List<T> list) {
this._list = list;
}
public void retainAll(Class<?> c) {
//..
}
public void removeAll(Class<?> c) {
//..
}
// Implement List<T> interface:
public boolean add(T element) {
return _list.add(element);
}
public void add(int index, T element) {
_list.add(index, element);
}
// etc...
}
Alternatively, if the methods don't need to access protected members, then static helper methods are a less clucky alternative:
public class FilterUtils {
public static void retainAll(List<T> list, Class<?> c) {
//..
}
public static void removeAll(List<T> list, Class<?> c) {
//..
}
}
What prevents you from just adding new methods to the interface?
If you can't just add the new functionality to old interface, you could consider making another interface and then an implementation which merely implements those two. Just to be clear, in code this is what I mean:
// Old functionality:
public interface Traveling {
void walk();
}
// Old implementation:
public class Person implements Traveling {
void walk() { System.out.println("I'm walking!"); }
}
// New functionality:
public interface FastTraveling {
void run();
void fly();
}
// New implementation, option #1:
public class SuperHero extends Person implements FastTraveling {
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
// New implementation, option #2:
public class SuperHero implements Traveling, FastTraveling {
void walk() { System.out.println("I'm walking!"); }
void run() { System.out.println("Zoooom!"); }
void fly() { System.out.println("To the skies!"); }
}
I think it's illegal because you can not guarantee what class T will be. Also there are technical obstacles (parent's class name must be written in bytecode, but Generics information get lost in bytecode).
You can use Decorator pattern like this:
class ListDecorator implements List {
private List decoratingList;
public ListDecorator(List decoratingList){
this.decoratingList = decoratingList;
}
public add(){
decoratingList.add();
}
...
}
class FilterByArrayList extends ListDecorator {
public FilterByAbstractList () {
super(new ArrayList());
}
}
There is a delegation/mixin framework that allows a form of this. You can define a new interface, implement a default implementation of that interface, then request classes which implement that interface but subclass from elsewhere in your hierarchy.
It's called mixins for Java, and there's a webcast right there that demonstrates it.
I'm afraid it's not clear what do you want to get.
Basically, I don't see any benefit in using 'public class NewFunctionality<T extends OldFunctionality> extends T' in comparison with 'public class NewFunctionality extends OldFunctionality' ('public class FilterByType<T extends List> extends T' vs 'public class FilterByType<T> implements List<T>')

Categories

Resources