4

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

Sandeep Kumar
  • 350
  • 4
  • 18

6 Answers6

3

Let's assume that you have a list of Animals. and you have Tigers and Lions 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.

xenteros
  • 15,586
  • 12
  • 56
  • 91
1

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.

fabian
  • 80,457
  • 12
  • 86
  • 114
1

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.

ChiefTwoPencils
  • 13,548
  • 8
  • 49
  • 75
0
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.

Hugo G.
  • 636
  • 6
  • 21
0

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.

Community
  • 1
  • 1
Linus
  • 894
  • 7
  • 13
-2
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.

Umair Farooq
  • 1,684
  • 2
  • 14
  • 25
  • They're asking for Java. `List` cannot be instantiated. Your examples of writing the names would not only not compile but goes against good polymorphic design. – ChiefTwoPencils Sep 02 '16 at 07:56
  • 2
    Not to mention you have down casting backwards. – Linus Sep 02 '16 at 07:58
  • @ChiefTwoPencils Thanks for pointing that out. I just gave a general example of using a collection. It was not language specific. Although they have put a tag of JAVA but in question they just asked a general question. – Umair Farooq Sep 02 '16 at 09:41
  • @Linus I didn't understand your comment. Can you please elaborate on that ? – Umair Farooq Sep 02 '16 at 09:43
  • @UmairFarooq, If B extends A, then casting from B to A is *upcasting*. Downcasting would be from A to B; the reverse of what you have in the second paragraph. Also... casting doesn't change the class. a is a type A reference to an object of class B. Upcast or downcast, the object is always of class B, only the type referenced in the compiler is being manipulated. – Linus Sep 02 '16 at 16:13