0

I currently have a Supercar class that extends a Car class, and want to downcast an array of Car class.

My code:

System.out.println("\nLab Task 6");
Car[] cars = new Car[10]; //object array
cars[0] = new SuperCar( model: "Lambo", cc: 8000, type: "Car", transmission: "Manual", powertrain: "Electric", maxSpeed: 300);
cars[1] = new SuperCar( model: "BMW", cc: 4500, type: "Car", transmission: "Manual", powertrain: "Electric", maxSpeed: 200);
Supercar superD = (SuperCar)cars[];

Is that any problem or error inside the code?

theduck
  • 2,589
  • 13
  • 17
  • 23

3 Answers3

0

First of all: it would be beneficial, if you did not include a screenshot but pasted the code directly with highlighting. By this, we can directly provide edited code which directly relates to your code in the question.

The general idea you are trying to realize is called widening in terms of treating an instance of a subclass as an instance of its superclass and it's perfectly fine to do this. The reverse action would be called narrowing. However, in terms of your code, you cannot cast an array of Objects to another Object, you would need to enter an index to access a car from your array, which you then cast to your specialized class SuperCar.

Something like this should work:

SuperCar superD = (SuperCar) cars[0];

Although you'll have to think of how to access all of the different cars in the array.

kopaka
  • 535
  • 4
  • 17
  • So it's mean if i want to do downcasting for the array part must create one by one to access the specific class? – Oscar Chua Wei Wen Nov 21 '19 at 11:34
  • @oscar I am really not sure what you are trying to achieve, since it was not clear form the initial question. If you want the whole array of cars, you can also cast the array via ```SuperCar[] superD = (SuperCar[]) cars;``` – kopaka Nov 21 '19 at 11:41
  • How do i call `SuperCar[] superD = (SuperCar[]) cars;` ? – Oscar Chua Wei Wen Nov 21 '19 at 11:50
0

You cannot cast array of objects to another object. You can try doing as below

     SuperCar d = (SuperCar) car[0];
priyanka hj
  • 79
  • 1
  • 2
  • 11
0

If you initialize an array with its own type:

Car[] cars = new Car[10];

even though Car is a superclass, you can not downcast the cars array. For this reason, below code will throw ClassCastException

SuperCar[] superD = (SuperCar[])cars;

If you want to downcast the Car array, you have to initialize this array with subclass type:

Car[] cars = new SuperCar[10];

and you can downcast this array to SuperCar.

SuperCar[] superD = (SuperCar[])cars;

Mustafa Çil
  • 766
  • 8
  • 15