Checking the Precedence of a Class with instanceof
You can check whether an object is an instance of a specific class. This can be convenient for things such as error checking, handling data in different ways depending on its precedence, and more. The following example shows the checkNumber
method, which can discriminate between different types of variables and will print different messages based on that:
public class Example04 { Â Â Â Â public static void checkNumber(Number val) { Â Â Â Â Â Â Â Â if( val instanceof Integer ) Â Â Â Â Â Â Â Â Â Â Â Â System.out.println("it is an Integer"); Â Â Â Â Â Â Â Â if( val instanceof Double ) Â Â Â Â Â Â Â Â Â Â Â Â System.out.println("it is a Double"); Â Â Â Â } Â Â Â Â public static void main(String[] args) { Â ...