Inheritance

A class is a kind of abstraction and we can define either general things or more specific ones.
For example, a car is a kind of vehicle and we can describe what is a vehicle, then what is a car or a truck, by defining attributes common to vehicles, and then by redefining the class for a car or a truck.
Vehicle will be called the "superclass" or "base class", and Car and Truck are subclasses of Vehicle.
Attributes and methods of the superclass are also that of the subclasses.

The syntax of inheritance is:

class name is supername

That means that the instances of the class "name" inherits attributes and methods of the superclass "supername".

Example of inheritance.

Car or Truck are subclasses of Vehicle.
class Vehicle
  int fuel
  void Vehicle()
    fuel = 100
  return
/class

class Car is Vehicle
  int passengers
  void Car()
    passengers = 3
    fuel = 50
  return
/class

class Truck is Vehicle
  int content
  void Truck()
    fuel = 200
    content = 1000
  return
/class

Truck bibendum
Car daisy

print bibendum.content  ` attribute of the Truck class
print
bibendum.fuel  ` attribute of the Vehicle superclass
print bibendum.passengers  ` bad! passengers non accessible from Truck!
print daisy.passengers  ` good, passengers is attribute of Car
Displays: > 1000
> 200
> 3


 Exercises

 

1) Write the two-places vehicle Buggy class, choose a class to inherit from among the classes described above, choose attributes and method to add or remove.
Create an instance "mycar" and display the number of passengers.

Answer