Reputation: 350
we can achieve the output in two ways one is typecasting and one is without typecasting
A a=new B() // without typecaste
A a = (A)a// with Typecaste
in both ways we get same output.so, what is the use of typecasting
Upvotes: 4
Views: 2010
Reputation: 1702
A a=new B()
is applicable only when class B
extends class A
. In this way the extra methods that are available in class B
other than class A
will be available with reference a
.
When you do this
A a = (A)a
Then actually you are down casting the object of class B
into an object of class A
. And it is true that child can be type cast to parent. After this statement the reference a
will not be able to call any method of class B
which were not in class A
because now the reference a
points to an object of class A
.
It is useful in many scenarios. For example, you want to have a collection of Objects that point to same base class. Instead of maintaining separate collections for each sub class, you maintain a single collection of base class. And then when you want to use any child object you type cast the base class object to child class object to do that.
ArrayList<Base> children = new ArrayList<Base>();
children.add(new Child1());
children.add(new Child2());
Console.WriteLine(((Child1)children.get(0)).getChildName());
Console.WriteLine(((Child2)children.get(1)).getChildName());
Now base class does not have any method named getChild1Name
or getChild2Name
. And you need to typecast object of base class to respective child class to do that.
Upvotes: -2
Reputation: 13940
Casting has different uses. Unfortunately, your example doesn't exercise any useful example of casting since you create an instance of A
(a
) then cast it to an A
.
What you need to understand is there are apparent types and actual types. An apparent type would be List<T> list;
. Here we see that it's a list. But the actual type might be an ArrayList<T>
(List<T> list = new ArrayList<>();
). In this scenario we can, with care, cast the apparent type to the actual type. This would allow us to then use the functionality of the actual type. For example, let's look at some code; given:
List<Integer> list = new ArrayList<>();
ArrayList<Integer> aList;
LinkedList<Integer> lList = new LinkedList<>();
We can do this without issue (although dangerous in general)...
// Dangerous but OK with a cast
// list might not be an ArrayList
aList = (ArrayList<Integer>) list;
// Use ArrayList methods
aList.trimToSize();
list = lList;
LinkedList<Integer> danger = (LinkedList<Integer>) list;
...but it's also possible to do:
aList = (ArrayList<Integer) list;
// Use ArrayList methods
aList.trimToSize();
// list = lList;
LinkedList<Integer> danger = (LinkedList<Integer>) list;
The last snippet results in a ClassCastException
because list
isn't a LinkedList
.
Casting goes beyond that though. Consider when you have two integers you want to divide. Without a cast you could end up with an integer result where a floating point is more appropriate. Consider:
int i = 2;
int j = 3;
System.out.println("No cast: " + i/j + " ;With cast: " + (double)i/j);
Output:
No cast: 0 ;With cast: 0.6666666666666666
So, it depends on the use case.
Upvotes: 1
Reputation: 894
Java implicitly upcast with assignment, so in the code you've provided the casting operator is redundant; a
is already of type A
:
A a = new B(); // without typecast operator (implicit upcast)
A a = (A)a; // with redundant typecast operator
One reason to have a casting operator is that you may also wish to downcast (which is not done implicitly in Java). For instance, when a
is a type A
reference to an object of class B
(e.g. when B
is a subclass of A
) one may need to downcast to access certain methods:
A a = new B(); // implicit upcast
C c = ((B)a).methodOfBOnly(); // explicit downcast
You may also want to check this question on why Java doesn't do implicit downcasting.
There can be times when upcasting needs to be done explicitly as well. For instance, if a class contains overloaded methods
C method(A x){/*does one thing*/}
C method(B x){/*does another*/}
and assuming b
is of type B
, the calls to method((A)b)
and method(b)
would behave differently.
Upvotes: 0
Reputation: 636
A a = new B();
will only works if B
inherit from A
.
If B
inherit from A
, the type cast is not required as B is a A. Type cast will be necessary if you need to type cast to a subclass:
A a = new B();
B b = (B) a;
While this would be illegal :
A a = new A();
B b = (B) a;
as a
is not a B
.
Upvotes: 0
Reputation: 82461
Casting is for "the opposite direction", i.e. for converting to a expression of a subtype of the original expression.
Example
Given
Object o = "Hello World";
String s = o;
does not compile, but
String s = (String) o;
compiles. This may yield a ClassCastException
however, e.g. if a Integer
was stored in o
.
Upvotes: 1
Reputation: 15852
Let's assume that you have a list of Animal
s. and you have Tiger
s and Lion
s in it.
ArrayList<Animal> animals = new ArrayList<>();
//add some Tigers and some Lions
//sort so Tigers are at the beggining of the list
Tiger t = (Tiger)animals.get(0);
Without casting you will get type missmatch at compile time. With a cast you only risk ClassCastException
which can be easy caught with a try-catch
It's just an example of a proper use of class casting in Java.
Upvotes: 3