I have a simple class Apple extends from another simple class Fruit.
At run-time, I could use
Fruit fruit = new Apple();
fruit.getClass();
to get the actual type of fruit object, which is Apple.class.
I could also use fruit instanceof Apple
, and fruit instanceof Fruit
to verify if this fruit object is an instance of Apple or Fruit. Both of these 2 expressions return true, which is normal.
But is there a way to determine precisely the declared type of fruit
identifier? Which in this case is Fruit
.
The declared type or compile-time type of a variable is the type that is used in the declaration. The run-time type or actual type is the class that actually creates the object. The variable nameList declared below has a declared type of List and an actual or run-time type of ArrayList .
Rules for defining Java IdentifiersThe only allowed characters for identifiers are all alphanumeric characters([A-Z],[a-z],[0-9]), '$'(dollar sign) and '_' (underscore). For example “geek@” is not a valid java identifier as it contain '@' special character. Identifiers should not start with digits([0-9]).
Identifiers in Java are names that distinguish between different Java entities, such as classes, methods, variables, and packages. Identifiers include the names of classes, methods, variables, packages, constants, etc. These identifiers are each specified using a specific syntax and naming scheme.
You're actually asking a question about the variable declaration of fruit
rather than the actual runtime type of the object (which is an Apple
in this case).
I think this is in general a bad idea: you just declared the variable and told the compiler that it is a Fruit
, so why do you need to now need to find this out?
Just to confuse matters even more, it's worth noting that you can also have multiple variables with different declared types referencing the same object (which is still an Apple):
Fruit fruit = new Apple(); // fruit declared as Fruit, but refers to an Apple
Object thing = fruit; // thing declared as Object, refers to the same Apple
If you really want to find out the declared type, then you have a few options:
fruit
an instance variable, and query the declared type using reflection.I think all of these are pretty ugly, so my general advice would be "don't do it".
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