/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Visitors
{
	public static void main (String[] args) throws java.lang.Exception
	{
        List<K> handlers = Arrays.asList(new K1(), new K2(), new K3());
        S sample = new A();
        for (K visitor : handlers) {
            sample.visit(visitor);
        }
        sample = new B();
        for (K visitor : handlers) {
            sample.visit(visitor);
        }
	}
}

interface K {
    void handle(A a);
    void handle(B b);
}
class A implements S {
    public void visit(K visitor) { visitor.handle(this); }
}
class B implements S {
    public void visit(K visitor) { visitor.handle(this); }
}

interface S {
    void visit(K visitor);
}
class K1 implements K {
    public void handle(A a) { System.out.println("K1 handling A"); }
    public void handle(B b) { System.out.println("K1 handling B"); }
}
class K2 implements K {
    public void handle(A a) { System.out.println("K2 handling A"); }
    public void handle(B b) { System.out.println("K2 handling B"); }
}
class K3 implements K {
    public void handle(A a) { System.out.println("K3 handling A"); }
    public void handle(B b) { System.out.println("K3 handling B"); }
}