JavaDeveloper
JavaDeveloper

Reputation: 5660

Which keyword in helps to determine subclass?

obj instanceof Arrays

would help be know if obj is instance of Arrays, but what i want to know if what operator to use to find if obj is a subclass of Arrays ?

Assume class Animal is super class of Dog.

Dog d = new Dog().

if (dog "which operator ? " Animal) would result in true ?

Upvotes: 1

Views: 34

Answers (3)

CupawnTae
CupawnTae

Reputation: 14580

instanceof will return true for subclasses as well. An instance of Dog is also an instance of Animal.

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240898

See isAssignableFrom()

Animal.class.isAssignableFrom(dog.getClass())

will return you true if Dog is child of Animal (either extends or implements)

this will help you if you have type determined at runtime, if it is fixed to check against type then you can use instanceof operator

also while using this method make sure to handle null

Upvotes: 2

CodeBlind
CodeBlind

Reputation: 4569

Jigar's solution is probably best, but you could probably do it this way too:

dog instanceof Animal && !dog.getClass().equals(Animal.class)

This will only return true if dog's class is a child of Animal but is not a base-level Animal instance.

Upvotes: 1

Related Questions