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) { ...