Interfaces - a solution to an ambiguous error

Let's look at the following example:

public class BothPaintAndPrintable implements Paintable,Printable{
    public void print() {}
    public void paint() {}
}
public interface Paintable {
    public void paint();
}

public interface Printable {
    public void print();
}

public class ITest {
    ArrayList<Printable> printables = new ArrayList<Printable>();
    ArrayList<Paintable> paintables = new ArrayList<Paintable>();
    public void add(Paintable p) {
        paintables.add(p);
    }
    public void add(Printable p) {
        printables.add(p);
    }
    public static void main(String[] args) {
        BothPaintAndPrintable a= new BothPaintAndPrintable();
        ITest t=new ITest();
        t.add(a);//compiliation error here
    }
}

What if I want to add instances BothPaintAndPrintablefor each of ArrayLists? One way is to overload the method with a parameter BothPaintAndPrintable, but I'm trying to see alternatives, as this can lead to code reuse. Anyone have any other idea?

+5
source share
4 answers

You need a third overload:

public <T extends Object&Paintable&Printable> void add(T t) {
  paintables.add(t);
  printables.add(t);
}

This does the erasure add(Object), so it does not conflict with other methods, but limits the input to constructors both Paintable, and so Printable.

(Guava Joiner Iterator Iterable, , .)

+7

add(Object o), instanceof Object .

Object , InvalidArgumentException .

+2

, , !

, "instanceof" :

import java.util.ArrayList;

class BothPaintAndPrintable implements Paintable, Printable {
    public void print() {
    }

    public void paint() {
    }
}

interface Paintable {
    public void paint();
}

interface Printable {
    public void print();
}

 public class ITest<T> {
    ArrayList<Printable> printables = new ArrayList<Printable>();

    ArrayList<Paintable> paintables = new ArrayList<Paintable>();

    public void add(T p) {
        if (p instanceof Paintable) {
            paintables.add((Paintable) p);
        }
        if (p instanceof Printable) {
            printables.add((Printable) p);
        }
    } 

    public static void main(String[] args) {
        BothPaintAndPrintable a = new BothPaintAndPrintable();
        ITest<BothPaintAndPrintable> t = new ITest<BothPaintAndPrintable>();
        t.add(a);
    }
}
0

, ; , .

public static void main(String[] args) {
    BothPaintAndPrintable a= new BothPaintAndPrintable();
    ITest t=new ITest();
    t.add((Paintable)a);
    t.add((Printable)a);
}

, .

0

All Articles