Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a form of "type safe" casting in Java?

Tags:

java

casting

Suppose I have two classes deriving from a third abstract class:

public abstract class Parent{     public Parent(){     } }  public class ChildA extends Parent {     public ChildA {     } }  public class ChildB extends Parent {     public ChildB {     } } 

In C# I could handle casting in a somewhat type safe manner by doing:

ChildA child = obj as ChildA; 

Which would make child == null if it wasn't a ChildA type object. If I were to do:

ChildA child = (ChildA)obj; 

...in C# this would throw an exception if the type wasn't correct.

So basically, is there a way to to do the first type of casting in Java? Thanks.

like image 466
garrettendi Avatar asked Dec 27 '11 22:12

garrettendi


People also ask

Is there type casting in Java?

Type casting is when you assign a value of one primitive data type to another type.

What are the two types of type casting in Java?

There are two types of casting in Java as follows: Widening Casting (automatically) – This involves the conversion of a smaller data type to the larger type size. Narrowing Casting (manually) – This involves converting a larger data type to a smaller size type.

How many types of type casting are present in Java?

The process of converting the value of one data type ( int , float , double , etc.) to another data type is known as typecasting. In Java, there are 13 types of type conversion.

What is Istype casting in Java?

Typecasting, also known as type conversion in Java, is a process that helps developers to assign a primitive data type value to other primitive data types. Here, compatibility is the key! Developers need to check whether a data type is compatible with the assigned data type or not.


1 Answers

I can't think of a way in the language itself, but you can easily emulate it like this:

ChildA child = (obj instanceof ChildA ? (ChildA)obj : null); 
like image 62
Aleks G Avatar answered Oct 11 '22 09:10

Aleks G