For this example:
public class Foo{} public class Bar extends Foo{} .... void myMethod(Foo qux){ if (checkInstance(qux,Foo.class)){ .... } }
How can I check if qux
is an instance of Foo (but not an instance of its subclass of foo)? That is:
Is there some kind of statement like instanceof
for this check? or I should use qux.getClass().equals(Foo.class)
Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .
Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.
In other words, isinstance is true for subclasses, too.
An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables.
If you have to do this, the only way would be the getClass().equals(Foo.class)
option you've suggested.
However, the goal of OO design is to allow you to treat any Foo
in the same fashion. Whether or not the instance is a subclass should be irrelevant in a normal program.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With