【发布时间】:2018-02-04 00:16:50
【问题描述】:
来自 JavaScript 背景,我发现以下代码有点过于健壮,包含多个语句;并且想知道如何简化代码,并在一条语句中完成所有操作。
Student 是超类,Friend 和 Schedule 是聚合成超类 ArrayList 公共成员的子类(这些不是嵌套类)。这是我当前的代码:
public static void main(String[] args) {
// Subclass1 instantiation and declaration
Friend friend_of_andy_1 = new Friend(1002, "Bob");
ArrayList<Friend> andys_friends = new ArrayList<>();
andys_friends.add(friend_of_andy_1); // superclass member
// Subclass1 instantiation and declaration
Schedule schedule_of_andy_1 = new Schedule(1, "Yoga practice");
ArrayList<Schedule> andys_schedule = new ArrayList<>();
andys_schedule.add(schedule_of_andy_1); // superclass member
// Superclass instantiation declaration with subclass objects in constructor argument
Student student_andy = new Student(1001, "Andy", andys_friends, andys_schedule);
}
我想知道是否可以这样做,在单个语句中声明/实例化超类和子类;这可能吗?
public static void main(String[] args) {
Student student_andy = new Student(
1001,
"Andy",
// instantiation of subclass
ArrayList<Friend>[
Friend(
{
1002,
"Bob"
}
)
],
ArrayList<Schedule>[
Schedule(
{
1,
"Yoga practice"
}
)
]
)
};
【问题讨论】:
-
你知道
Arrays.asList(foo, bar, baz)吗? -
@DawoodibnKareem 是的……你能不能把 foo 写成实例化/声明……像这样:Arrays.asList(new_foo(arg1, arg2), bar, baz) ??
-
您为什么不尝试一下,然后在此处发表评论,说明您的进展如何?
标签: java inheritance subclass aggregation