Issue
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.
Solution
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);
Answered By - Aleks G
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.