Java确定对象是哪个类 [英] Java determine which class an object is

查看:110
本文介绍了Java确定对象是哪个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个课程( Carnivore Herbivore Plant )扩展另一个类( Organism )。我如何知道一个对象是哪个子类的一部分?到目前为止,我有一个属性具有类的名称,但我认为可以使用类似于javascript的typeof的运算符。 (类似于: Carnivore的有机体类型

I have three classes (Carnivore, Herbivore, and Plant) that extend another class (Organism). How can I tell which subclass an object is a part of? So far I have a property that has the classes' name, but I think it could be possible to use an operator similar to javascript's typeof. (Similar to: Organism typeof Carnivore)

推荐答案

instanceof 关键字。

但是,需要使用这通常是一个糟糕的设计的迹象。您通常应该在每个派生类中编写方法覆盖,以便您不需要显式地检查哪个类是什么。

Note, however, that needing to use this is often a sign of a bad design. You should typically write method overrides in each of your derived classes so that you don't explicitly need to check which class something is.

这篇关于Java确定对象是哪个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆