我有一些Java代码,我想转移到ABAP中。我在属性和构造函数声明/实现方面苦苦挣扎。
如何在 ABAP 中表示下面的 Java 代码?
class Node {
private String data;
private Node[] children = new Node[0];
private Node parent = null;
public Node(String data) {
this(data, null);
}
public Node(String data, Node child) {
this.data = data;
if (child != null) {
this.addChild(child);
}
}
}
这是你能得到的尽可能接近的:
CLASS node DEFINITION
PUBLIC CREATE PUBLIC.
PUBLIC SECTION.
METHODS constructor
IMPORTING
data TYPE string
child TYPE REF TO node OPTIONAL.
PRIVATE SECTION.
DATA data TYPE string.
DATA children TYPE STANDARD TABLE
OF REF TO node WITH EMPTY KEY.
DATA parent TYPE REF TO node.
ENDCLASS.
CLASS node IMPLEMENTATION.
METHOD constructor.
me->data = data.
IF child IS BOUND.
INSERT child INTO TABLE children.
ENDIF.
ENDMETHOD.
ENDCLASS.
ABAP 不支持重载,这意味着您不能具有具有不同输入参数集的方法的多个变体。
你不能"完全"做你想做的事。ABAP不像大多数OO语言那样是完全多态的。
不能有 2 个具有不同签名的构造函数。
您可以使用带有可选参数的构造函数并获得非常相似的结果。
试一试,看看您管理的内容并再次发布。
让我提出另一个选项,如果你有多个构造变体并且想要阻止可选参数:
CLASS node DEFINITION
PUBLIC CREATE PRIVATE.
PUBLIC SECTION.
CLASS-METHODS create_with_data
IMPORTING
data TYPE string
RETURNING
VALUE(result) TYPE REF TO node.
CLASS-METHODS create_with_data_and_child
IMPORTING
data TYPE string
child TYPE REF TO node
RETURNING
VALUE(result) TYPE REF TO node.
PRIVATE SECTION.
DATA data TYPE string.
DATA children TYPE STANDARD TABLE
OF REF TO node WITH EMPTY KEY.
DATA parent TYPE REF TO node.
METHODS constructor
IMPORTING
data TYPE string
child TYPE REF TO node OPTIONAL.
ENDCLASS.
CLASS node IMPLEMENTATION.
METHOD create_with_data.
result = NEW #( data = data ).
ENDMETHOD.
METHOD create_with_data_and_child.
result = NEW #(
data = data
child = child ).
ENDMETHOD.
METHOD constructor.
me->data = data.
IF child IS BOUND.
INSERT child INTO TABLE children.
ENDIF.
ENDMETHOD.
ENDCLASS.