0

I am a bit confused in understanding the casting concept in java. Here is a piece of code that I have written.

class Parent {
    public int a = 5;
    public void print()
    {
        System.out.println("a :: " + a);
    }
}
class Child extends Parent
{
    public int b = 10 ; 
    public void printMe()
    {
        System.out.println("a :: " + a + " b::  " + b);
    }
}

public class Main  {
    public static void main(String[] args) {

        Child b = new Child();
        Parent a = (Parent)b;
        Child b1 = (Child)a;
        b1.printMe(); // This piece of code works fine. There is no exception


        Parent a1 = new Parent();
        Child b2 = (Child) a1;
        b2.printMe(); //This piece of code throws a java.lang.ClassCastException
    }
}

In the first piece of code I am creating a child object and typecasting it to parent. When I typecast the parent object to child again It works fine. But in the other piece of code I am creating a Parent object first and then typecasting it to child. Compiler doesn't show any error. But when I run the code It is throwing ClassCastException. Can someone explain me why is it so ? If there is no problem with first piece of code means second one also should work fine right ? I am so confused. And one more question is when do we assign a child object to a parent reference ? I mean for example if we write a code like below

Parent p = new Child();

which is equal to the following code right ?

Parent p = new Parent();

Then what is the benefit in writing such code ?

KarthickN
  • 335
  • 1
  • 6
  • 20

0 Answers0