|
We use overloading when
we want to use the same method name for different types of data. For example,
+ sign is already overloaded as it adds integers, doubles and it also concatenates
strings, which is a kind of addition operation. However, Java does not
support operator overloading, except the case explained above. Because,
experience have shown that, operator overloading is making multi-person
programming projects infeasible.
Reusability of code
segments is one of the main advantages of object-oriented programming languages.
An object can inherit methods and fields from another object. It keeps
those it wants and omits or replaces the others.
We can define a MotorVehicle
class:
class MotorVehicle
{
private String licensePlate; // e.g. "New
York A456 324"
private double topSpeed;
// kilometers per hour
private String make;
// e.g. "Ford"
private String model;
// e.g. "Taurus"
private int productionYear; //
e.g. 1997, 1998, 1999, 2000, 2001, etc.
private int numPassengers; // e.g. 4
private int numWheels;
// all cars have four wheels
private int numDoors;
// e.g. 4
// other methods...
}
Then, we can define
a Car class as a subclass of MotorVehicle class as:
class Car extends
MotorVehicle {
private int numWheels = 4; // all cars have 4 wheels
// methods...
}
and also
class MotorCycle
extends MotorVehicle {
protected
int numWheels = 2;
protected
int numDoors = 0;
// methods
}
These definitions are
complete; because both Car and MotorCycle methods inherits all of the fields
and methods from their superclass: MotorVehicle.
We can go further
levels of inheritance if the structure needs.
Multiple Inheritance
allows inheriting fields and methods from more than one unrelated classes.
When we defined a subclass,
we can use superclass' methods and fields. However, some changes might
be necessary for method, say X. Then, we can reimplement this method so
that subclass has its own X method.
|