Type casting in Java is the process of converting a data type to another data type in both ways, manually (explicit) or automatically (implicit). There are two types of type casting, widening and narrowing.
Widening
Widening converts smaller data type is converted to a larger data type. This type of casting is safe and does not lead to data loss.
10.0
Narrowing
Narrowing casting, it is often done manually by the programmer. It happens when a larger data type is converted to a smaller data type. It may cause data loss.
10
Casting floating point number to integer number leads to the lose of fractional part.
Type casting between reference types
Type casting can also occur between reference types, primarily involving class hierarchies and interfaces. There are two types of type casting between reference types.
Upcasting
Converting a subclass type to a superclass type.
Here, the upcasting is implicit, without a cast operator.
Downcasting
Converting a superclass type to a subclass type. This is explicit and requires a cast operator.
Dynamic method dispatch
Type casting between reference types is often used in Dynamic Method Dispatch (Runtime Polymorphism), where which method will be called for an object will be determined at runtime.
A displayed
Here, the displayB()
method cannot be called because the obj
is referenced to A
.
To call the displayB()
method, the object has to be casted to B
.
B displayed
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaType_CastingWideningNarrowingUpcastingDowncasting