explain subclasses and polymorphism car and


Explain Subclasses and Polymorphism ?

Car and Motorcycle are subclasses of MotorVehicle. If you instantiate a Car or a Motorcycle along with new, you can use in which object anywhere you can use a MotorVehicle, since cars are motor vehicles. As same you can use a Motorcycle anywhere you can use a MotorVehicle. This use of a subclass object in place of a superclass object is the starting of polymorphism. I'll say more about polymorphism later.

The converse is not true. While all cars are motor vehicles, not all motor vehicles are cars. A few are motorcycles. Thus if a method expects a Car object you shouldn't provides it a MotorVehicle object instead.

Remember that I said you shouldn't provide a method in which expects a Car a MotorVehicle. I didn't say you couldn't. Objects can be cast into their subclasses. This is useful while using data structures like Vectors that only handle generic objects. It's up to the programmer to remain track of what kind of object is stored in a Vector, and to use it accordingly.

The proper choice of classes and subclasses is a skill learned primarily by experience. There are often different ways to define classes.
toString() as example of polymorphism

Request for Solution File

Ask an Expert for Answer!!
JAVA Programming: explain subclasses and polymorphism car and
Reference No:- TGS0284733

Expected delivery within 24 Hours