0

I've been learning about inheritance in Java and am not certain if you can cast a Parent object into a Child object. I would have thought that was okay (but the other way around was a no-no), but after reading up on the topic, I think that this cannot be done. I'd like to ask the forum if I am correct.

Suppose I have a program called FruitCart which works with a lot of class Fruit objects:

public class Fruit{
    String color;
    boolean hasSeeds;

    public Fruit(String a, boolean b){
        this.color = a;
        this.hasSeeds = b;
    }
}

public class FruitCart{
    public static void main(String[] args){ 
        Fruit fruitA = new Fruit("red", true);
        Fruit fruitB = new Fruit("yellow", false);
        ...many more...
    }
}

Okay. Now suppose that as my program continues, it learns more properties about the fruit in the cart. For example, maybe my program learns that fruitA is of type "Red Delicious." We now know that fruitA is an apple, and it would be great to convert fruitA from an instance of class Fruit to an instance of class Apple:

public class Apple extends Fruit{
    String type;

    public Apple(String a, boolean b, String c){
        super(a, b);
        this.type = c;
    }
}

My question is... is it impossible to cast fruitA from a Fruit to an Apple object?

public class FruitCart{

    public static void main(String[] args){

        Fruit fruitA = new Fruit("red", true);

        fruitA = new Apple(, "Red Delicious");    // nope
        ...or...
        fruitA = (Apple)fruitA;                   // no good
        ...or...
        Apple appleA = (Apple)fruitA;             // nada

    }
}

I've been Googling for this for over an hour, and as I said, I think that the answer is no. This post alone made me think so:

Casting in Java(interface and class)

However, I am not experienced enough to know if the materials I'm reading directly correlate to the issue I'm describing here. Can folks here confirm?

Many thanks, -RAO

Community
  • 1
  • 1
Pete
  • 1,511
  • 2
  • 26
  • 49
  • You can always cast from children to parent since by inheritance Apple is a Fruit however a Fruit may not be an Apple. You can cast a Fruit to an Apple however it's better to check (using intansceof or comparing the class) to see if that cast is possible. Also you can only cast down if the object was created as the a children, basically you'd have to do Fruit fruitA = new Apple(arguments); then you could do Apple apple = (Apple)fruitA; and it would work. – DMH May 02 '16 at 02:54
  • `fruitA = new Apple(, "Red Delicious");` This line has a syntax error (the extra comma/missing arguments). It should work. – markspace May 02 '16 at 02:55

2 Answers2

0

You can only cast a reference with a given type to a reference of another given type if the instance that the "source" reference refers to is the same type or a subtype of the type of the "destination" reference.

If you have

public class A {}

public class B extends A {}

public class BB extends A {}

public class C extends B {}

then the following will work:

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

By contrast, none of these will work:

A a = new BB();
B b = (B) a;
C c = (C) a;

And remember that even in the cases that do work, the cast is not changing anything. All it changes is the type of the reference by which you are referring to the instance. It does nothing whatsoever to the instance. It does not "convert" instances in any way.

QuantumMechanic
  • 13,795
  • 4
  • 45
  • 66
-1

You cannot cast(convert) a PARENT class to a CHILD class unless the PARENT class holds an instance of CHILD class or its derived classes.

public class Parent{ 
    public String getNameOfClass(){
      return "Parent";
    } 
}  // parent class
public class Child extends Parent{
   public String getNameOfClass(){
      return "Child";
    }
}  // child class

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Parent p = new Child();
     Child c = (Child) p;
    System.out.println(c.getNameOfClass());
}

The output is child.

From Wikipedia

Many people advocate avoiding downcasting, since according to the LSP, an OOP design that requires it is flawed.[citation needed] Some languages, such as OCaml, disallow downcasting altogether.[1]

A popular example of a badly considered design is containers of top types, like the Java containers before Java generics were introduced, which requires downcasting of the contained objects so that they can be used again

So we can see if the Parent object is instantiated as the Child class then it will work and will compile, however if it is not done so it will give a compile time error.

Pritam Banerjee
  • 17,953
  • 10
  • 93
  • 108
  • 5
    Very poorly expressed. You cannot cast a *reference* which is *typed as* a parent class reference unless it actually refers to an instance of the child class. You cannot convert classes at all with this syntax. – user207421 May 02 '16 at 03:09
  • @EJP it is in Wikipedia and as I hae mentioned if only Parent has an instance of it's child only then it will be possible – Pritam Banerjee May 02 '16 at 03:11
  • @EJP Code compiles and runs fine. So what is the problem? Not the best thing to do, that is different but it will work – Pritam Banerjee May 02 '16 at 03:30