How do i call functions from extending classes, when i have an array of the abstract objects?

class CNN {
  Layer[] layers=new Layer[2];

  CNN() {
    layers[0]=new RED();
    layers[1]=new BLUE();

    for (int i=0; i<layers.length; i++) {
      switch (layers[i].name) {
      case"RED":
        layers[i].some_function();   // How do i do something like this ?
        break;
      case"BLUE":
        layers[i].some_other_function();
        break;
      }
    }
  }
}

abstract class Layer {
  String name;
  abstract String getName();
}

class RED extends Layer {
  RED () {
    name="RED";
  }
  String getName() {
    return name;
  }
  void some_function() {
    println(name);
  }
}

class BLUE extends Layer {
  BLUE () {
    name="BLUE";
  }
  String getName() {
    return name;
  }
  void some_other_function() {
    println(name);
  }
}

Answers

  • Answer ✓

    How does it know which class the object is in lines 11 and 14? It needs to in order to know that it can call the non interface methods on this item.

    Try casting the objects.

  • Can't classes RED & BLUE simply share the same name for their 2nd method just like you did for getName(), so that method can also be abstract inside Layer? :>

    abstract class Layer {
      String name;
      abstract String getName();
      abstract void some_function();
    }
    
  • edited July 2017

    GoToLoop no, those are just example methods, the actual methods are different. koogs yes that worked, thanks

    for anyone one with the same problem; (don't forget the instanceof)

    switch (layers[i].name) {
          case"RED":
            if (layers[i] instanceof RED) {
              ((RED)layers[i]).some_function();
            }
            break;
          case"BLUE":
            if (layers[i] instanceof BLUE) {
              ((BLUE)layers[i]).some_other_function();
            }
            break;
          }
    
Sign In or Register to comment.