Home > Software design >  Sparrow spw= (Sparrow) new Bird(); what does the line mean?
Sparrow spw= (Sparrow) new Bird(); what does the line mean?

Time:10-29

where Sparrow and bird both are different classes and Sparrow class is an extended class of Bird class.

I just wanna see if i create an instance of Class Sparrow does it can implement the property of the Bird object.

CodePudding user response:

This line means the same thing as

throw new ClassCastException();

which is to say that it always fails and will never work.

To create a Sparrow, you must write new Sparrow() or new SomeSubtypeOfSparrow().

CodePudding user response:

It doesn't really make sense to do this. You are creating a generic Bird, and then casting it to a Sparrow. Since it is not a Sparrow (nor any subclass of Bird), it throws an exception when you try to do this.

  •  Tags:  
  • java
  • Related