【发布时间】:2019-10-05 11:30:14
【问题描述】:
我有父类和两个子类。
我想在我的方法checkType(List<Parent>) 中创建一个条件
我的主要课程
Parent.getClass() 是返回 Child1 还是 Child2
假设我有存储所有对象的列表。
所以 checkType 方法可以计算 List 中有多少 child1 和 child2。
abstract class Parent
{
...
public Parent getClass
{
...
}
}
class Child1 extends Parent
{
...
}
class Child2 extends Parent
{
...
}
【问题讨论】:
-
那么
checkType在哪里以及如何使用它? -
在我的主课上说吧。我想比较它是否是child1然后返回true
-
对不起,我不清楚你在这里想要达到什么目的。我看不出
getClass返回Parent类型的对象的意义,对于您所描述的,它应该是一个字符串,不应该是吗?如果您想在 Main 类中知道Parent的某个实例的具体类型是什么,只需在那里使用instanceof......但是在Parent类中方法getClass的意义何在?请让您的问题更清楚,以便更好地帮助您。 -
是的,这就是我想问的。谢谢
-
@lealceldeiro 我已经编辑了我的问题。我知道使用 instanceOf 是答案。我只是想让大家更清楚。
标签: java inheritance return-type