Question about virtual methods in java

Simply put: I want the following code to print "sub":

Element e = new SubElement();
print(e);
... 

private static void print(Element e) {
    System.out.println("e");
}

private static void print(SubElement e) {
    System.out.println("sub");
}

and I do not want to change the print (element e). so nothing like that

private static void print(Element e) {
    if (e instanceof SubElement) {
        print((SubElement) e);
    } else {
        System.out.println("e");
    }
}

what i would like to do is

print(e.getClass().cast(e));

to automatically apply it to a real subclass and force the system to enter printing (SubElement e). is this somehow possible?

+3
source share
5 answers

Yes. You can use the visitor template . However, it is suitable for fixed, well-defined hierarchies, since the Visitor interface you must define requires a method for each type.

interface ElementVisitor {
   visit(Element e);
   visit(SubElement se);
}

class ElementerPrinter implements ElementVisitor {
   visit(Element e) { System.out.println("e"); }
   visit(SubElement e) { System.out.println("sub"); }
}

class Element {
  // here the trick, Element knows that this is Element
  // and childs have to implement it!
  // if the parent-most class is an interface it force you to implement!
  accept(ElementVisitor visitor) { visitor.visit(this); } 
}

class SubElement {
  // here the trick, Element knows that this is SubElement
  accept(ElementVisitor visitor) { visitor.visit(this); }
}
+1
source

, , , Element, SubElement. , , .

class Element {

    public String getName() {
        return "e";
    }
}

class SubElement extends Element {
    public String getName() {
        return "sub";
    }
}

:

private static void print(Element e) {
    System.out.println(e.getName());
}

, , Element .

+7

print() Element. . , if Class . ?

+1

?

Element e = new SubElement();
print(e);
... 

private static void print(Element e) {
    System.out.println(e.getMessageToPrint());
}

// no longer needed
//
//private static void print(SubElement e) {
//    System.out.println("sub");
//}

, SubElement getMessageToPrint().

:

Element e = new SubElement();
e.print();
0

.

  • use polymorphism as suggested by others, add an element to add the print () method (which can be overwritten by subclasses) or
  • Define a helper interface and use a combination of strategy and factory pattern:

Base class

 public class Element{}

Derived class

 public class SubElement extends Element{}

Helper interface for printing items

public interface PrintHelper{
    void print(Element element);
}

Factory to get the best PrintHelper for this item

public class PrintHelperFactory{

    private final Map<Class<? extends Element>, PrintHelper> registeredHelpers =
        new HashMap<Class<? extends Element>, PrintHelper>();

    // Register a PrintHelper for a given Element class.
    public void registerHelper(final Class<? extends Element> clazz,
      final PrintHelper helper){
        this.registeredHelpers.put(clazz, helper);
    }

    // Get the most specific PrintHelper for a given Element.
    public PrintHelper getHelperForElement(final Element element){
        Class<? extends Element> clazz = element.getClass();
        while(!Object.class.equals(clazz)){
            if(this.registeredHelpers.containsKey(clazz)){
                return this.registeredHelpers.get(clazz);
            }
            clazz = (Class<? extends Element>) clazz.getSuperclass();
        }
        return null;
    }

}

Client test class running as a Java application

public class Main{

    public static void main(final String[] args){

        final PrintHelperFactory factory = new PrintHelperFactory();
        factory.registerHelper(Element.class, new PrintHelper(){
            @Override
            public void print(final Element element){
                System.out.println("Element");
            }
        });
        factory.registerHelper(SubElement.class, new PrintHelper(){
            @Override
            public void print(final Element element){
                System.out.println("Sub Element");
            }
        });

        // test it with an Element  
        final Element elem = new Element();
        factory.getHelperForElement(elem).print(elem);

        // test it with a sub class
        final Element sub = new SubElement();
        factory.getHelperForElement(sub).print(sub);

    }

}

Output

Element
Sub Element
0
source

Source: https://habr.com/ru/post/1761699/


All Articles