Sunday 5 May 2013

What is Casting ???

Casting lets you convert one type of value into another.
In general terms casts can be implicit as well as explicit.
Let's dig some more into it ...

Implicit casts are those for which you do not have to write the code yourself i.e. it happens automatically. for Explicit casts code is required to be written by the developer.

Implicit casts are the often termed as widening conversions, for a smaller value can always be put into a larger container if the semantics of the data types involved are appropriate.

Explicit casts are used for narrowing conversions where a larger value is to be fit into a smaller container. Again the semantics of the involved data types must be appropriate.

Casting can be described in terms of
1. Primitive Data Types
2. Reference  Variables

Let's talk about Primitive Data Type Casting first...

int a = 100;
long aa = a; // Implicit cast, an int can always fit in a long

float f = 100.234;
int i = (float)f; // Explicit cast, float will loose it's decimal notation

In the above two examples Implicit and Explicit casts are shown in their simplest forms... let's see a few more examples to understand.

int i = 100.234; // error; a cast is very much required.
int i = (int) 100.234; // works

Let's take a look at casting involving Reference Variables

Suppose, we have this hierarchy ... 
Animal >>> Mammal >>> Dolphin

Dolphin dolphin = new Dolphin();
Mammal mammal = dolphin;
Animal animal = mammal;

Above written code is a classic example of an Implicit casting or sometimes also referred to as Upcasting.



if(animal instanceof Mammal) {
    mammal = (Mammal) animal;
}

Above code is an example of an Explicit cast or a Downcast.

In case of an Upcast, an error can only arise if the two reference variables do not fall in the same hierarchy or if the container reference falls below in the same hierarchy.

Implicit cast also comes with a small cost. When you upcast a reference variable, it can then only call those methods and only access those data members which are a part of the new Reference type.

Class Animal { // Animal Class
 public int getLegs() {
   return 4;
 }
}

Class Mammal extends Animal { // Mammal Class
 public int getEyes() {
   return 2;
 }
}

Class Test {
   public static void main(String... s) {
     Mammal mammal = new Mammal();
     Animal animal = mammal; // correct, legal
     
     mammal.getLegs(); // correct 
     mammal.getEyes(); // incorrect, Eyes() is a part of the mammal class
   }

In the above example mammal.getEyes() will throw an Exception at runtime because Animal class has no knowledge of the getEyes() present in the Mammal class. Reference variable "animal" can only be used to call those methods which are present in the Animal Class only.



No comments:

Post a Comment