4

Let's say:

class A {
    public int fieldA = 0;
}

class B extends A {
    public int fieldB = 0; 
}

Now, I want to create a instance of B from A:

A a = new A();
B b = (B) new A();

This gives a classCastException. I can make a costructor in B that takes a A instance and copy fields, but it's clearly non pratical:

class B extends A {
    public int fieldB = 0; 

    B (A a){
        fieldA = a.fieldA;
    }
}

Thank you for your help

DeliriumTremens
  • 340
  • 5
  • 14
  • 2
    What's the question exactly? It's quite obvious that you can't pretend that any Object is a List a Map, a Car or a Socket. So if you want a Car, you must create a Car. Creating an Object and casting it to a Car won't magically make it a Car. – JB Nizet May 30 '13 at 09:48
  • possible duplicate of [explicit casting from super class to subclass](http://stackoverflow.com/questions/4862960/explicit-casting-from-super-class-to-subclass) – Alya'a Gamal May 30 '13 at 11:16

6 Answers6

8

Take the following example

public class Animal
{
  public void eat(){}
}
public class Dog extends Animal
{
  public void eat(){}
  public void main(String[] args)
  {
    Animal animal=new Animal();
    Dog dog=(Dog) animal; //will not work
  }
}

By using a cast you're essentially telling the compiler "trust me. I'm a professional, I know what I'm doing and I know that although you can't guarantee it, I'm telling you that this animal variable is definitely going to be a dog."

Since the animal isn't actually a dog (it's an animal, you could do Animal animal = new Dog(); and it'd be a dog) the VM throws an exception at runtime because you've violated that trust (you told the compiler everything would be ok and it's not!)

The compiler is a bit smarter than just blindly accepting everything, if you try and cast objects in different inheritence hierarchies (cast a Dog to a String for example) then the compiler will throw it back at you because it knows that could never possibly work.

Because you're essentially just stopping the compiler from complaining, every time you cast it's important to check that you won't cause a ClassCastException by using instanceof in an if statement (or something to that effect.)

In your case you are saying my reference b will point to object of point B and then you make it point to object of class A(which is not object of class B that reference b was expecting). Hence you get the classCastException.

You could do something like

A a = new B();
B b = (B) a;
Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
1

The use for Class cast is something different.

class Employee()
{
    //body
}

class SalariedEmployee extends Employee()
{
    //body
}

You have some polymorphic code.

public static void met(Employee e)
{
    SalariedEmployee s = (SalariedEmployee)e
}

public static void somemethod()
{
    //You write a polymorphic method
    //You will create a list of Employees
    //Then you can write
    ArrayList<Employee> employees = new ArrayList<Employee>()

   //Create a SalariedEmployee
   Employee e = (Employee) new SalariedEmployee()
   employees.add(e);

   e = (Employee) new CommissionEmployee()
   employees.add(e);         

}

You can't do SalariedEmployee b = (SalariedEmployee) new Employee(); because every Employee is not guaranteed to be a SalariedEmployee.

Akshar Raaj
  • 14,231
  • 7
  • 51
  • 45
1

Try this, It will help you. I'll show you small demo that u can implement in your program.

//Inheitance Pass Reference of Child class into Super class object
class A
{

    void display()
    {
        System.out.println("\n\nSuper class A Dispaly method.");
    }
}

class B extends A
{

    void display1()
    {
        System.out.println("\n\nDerived class B Dispaly method.");
    }

    public static void main (String args[])
    {
        A objA = new A();
        objA.display();

        A a1;
        B b1 = new B();

        //Here is your answer.
        a1=b1;  //Dynamic Method Distpatch
        //a1 = new B(); //This will also work. //Dynamic Method Distpatch

        a1.display1();      
    }
}
Bhushankumar Lilapara
  • 780
  • 1
  • 13
  • 26
1

A isn't actually B (not every A is B , but all B is A)

You can do it like that :

 A a = new B();
 if (a instanceof B) {
     B dog = (B) a;
 }
Alya'a Gamal
  • 5,624
  • 19
  • 34
1

Let's say you got Animal and Dog extends Animal. You can say "a dog is an animal" (Animal animal = new Dog()) but you can't say "an animal is a dog" (Dog dog = new Animal()).

An Animal could also be a Cat or whatever, while a Dog or a Cat is necessarily an Animal.

sp00m
  • 47,968
  • 31
  • 142
  • 252
0

Also Child is always aware of parent which is done by using extends keyword but parent has no knowledge about child. When following is written:

A a = new B();

due the extends clause in child, compiler is able to assign reference of child to parent which is resolved at compile time itself. Inheritance relation is resolved at compile time itself. Casts in Java affect only the treatment of references; they never change the form of the actual object. The object pointed to by a reference is never changed by casting it, only the compiler's (or run-time system's) notion of it is changed.

Harish Kumar
  • 528
  • 2
  • 15