Docstoc

inheritance

Document Sample
inheritance Powered By Docstoc
					An alternative view of class
 inheritance and interfaces
          Objects and classes in the real world
In the real world, people use objects to do things.
      For example, you might have ridden here on your bicycle: a
       particular, specific, concrete object.
In the real world, objects are grouped into classes:
    Everybody’s individual bicycle is a member of the class bicycle.
Real-world objects group into classes because they all share
properties & abilities that define those classes:
    all bicycles can carry people,
    all bicycles can be steered,
    all bicycles can speed up or slow down.
    all bicycles have two wheels,
   all bicycles have pedals.

 In the real world, to make a new object (build a new bicycle), we
construct a thing with the properties & abilities of the class we want.
If we know some object is a member of a class, we can tell what
properties and abilities it has, and how to use it.
          Objects and classes in Java
In java, programs do things with and to objects.
· For example, if I want to use a description of my bicycle in a program, I
have to create a bicycle object to represent my bicycle. To represent your
bicycle, I need another bicycle object for it.
 In Java, objects are grouped into classes:
· Every bicycle object in my program is a member of class bicycle.
All java objects that are a member of a class have the properties (variables) &
abilities (methods) that define that class. For class bicycle:
   void Turn_left();                    void Turn_right();
   int handlebar_direction;
   void Speed_up()                      void Slow_down();.
   int pedal_turns_per_min;
   int front_wheel_size                 int back_wheel_size;

To make a new object, we construct a new member of a class
        bicycle newBike = new Bicycle();.
 If we know an object is a member of a class (e.g. if it is in a variable of
type bicycle), then we know what variables and methods the object has.
 In the real world, and in Java, the objects in a class (the members
 of the class) all have the properties (variables) and abilities
 (methods) which define that class.
class Bicycle (every dot inside the circle has all the
variables and methods that define a bicycle)
                                                      class Bicycle

  Bicycle objects
  (each dot represents
  a different particular
  bicycle)




 These outsiders are not members of the class (they do not have
 the required properties and abilities, or variables and methods).
 In the real world, classes have subclasses (types) and superclasses
 (broader groupings). Some subclasses (types) types of Bicycle
 are tandem and racer. Bicycle itself is a subclass of the
 broader superclass vehicle.
                      class Bicycle
A subclass: tandem
Since tandems are a type of
bicycle, they have all
properties and abilities that
define bicycles. But they
have further, more specific
properties, which define the
subtype tandem (i.e. carrying
two people, having two seats)
                                                         The superclass
  The subclass racer: all the properties of
                                                         of vehicles.
  bicycles, and some extra that define the subclass.
  In java, the relationship between subclasses and superclasses is
  given by the keyword extends.
 Every dot (object) inside the Bicycle circle (class) has all the
 variables and methods that define a bicycle. Since Bicycle is
 inside (extends) vehicle , those objects also have all the variables
 & methods of vehicles.
                             class Bicycle extends Vehicle

Class Tandem extends Bicycle
As well as having all the variables
 & methods of class Bicycle,
each Tandem object has
String frontPerson;
String backPerson;
void speedup_front();
void speedup_back();
etc. (methods and variables
specific to tandems)              Class Racer
                                extends Bicycle       class vehicle.
In our drawings, class Bicycle extends vehicle.
We should have a class definition for vehicle; Bicycle inherits
methods & variables from that.

What would be in a class definition for vehicle?

Remember, the vehicle class should include
 cars,
 airplanes,….
 Ships,

all sorts of things that are very different from bicycles.

All have certain common characteristics because they are vehicles:
they move, turn, carry people…

But all these things will have different particular ways of turning,
different ways of speeding up and down etc.
abstract class Vehicle{
  int num_seats, num_people; // some vars for class:
  int curr_X, curr_Y;        // location of vehicle
  int curr_angle;            // direction it‟s pointing

    Vehicle(){
        curr_X = 0;    curr_Y = 0;
        curr_angle = 0; }      // constructor

    int distance_to(int loc_x, loc_y){
       return sqrt((loc_x–curr_x)^2 +(loc_y–curr_y)^2) }

abstract   void   Turn_left(); These abstract methods are
abstract   void   Turn_right();
abstract   void   Speed_up();   undefined: they must be given
abstract   void   Slow_down(); definitions in subclasses of
                                  vehicle. Different types or
}                                 subclasses of vehicle will define
                                  these methods in different ways.
Class Bicycle extends Vehicle{            // location, angle,
int pedal_turns_per_min;                 // seats, etc. inherited
int handlebar_direction;

    Bicycle(){
     super();              //constructs a vehicle
     num_seats = 1;
     pedal_turns_per_min = 0;
     handlebar_direction = 0; }

    void Turn_left(){ handlebar_direction++;                 }

    void Turn_right() { handlebar_direction--; }

}                             // and many other methods …
Class Airplane extends Vehicle{
int fuel, tail_angle;      // location, angle, seats
int left_flap_angle; // people, are all inherited
int right_flap_angle;

     Airplane(){
     super();                  //constructs a vehicle first
     fuel = 10000;                num_seats = 200;
     left_flap_angle=0;       right_flap_angle=0;
     tail_angle=0;}

    void Turn_left(){ left_flap_angle++;
                      right_flap_angle--;
                      tail_angle--;
                      speed_up();
    }                    //and many other methods
}
What can go into a superclass variable?
Vehicle V;                      Only objects that are members of
                                Vehicle can go into this variable V.
 V = new Bicycle(); Create a new Bicycle object and
                                put it into variable V.
This works because Bicycle is a subclass of the class Vehicle.
 V = new Airplane(); Same idea: create a new Airplane
                                 object and put it into variable V.
If we have a variable of a particular superclass, objects from any of its
subclasses can go in the variable (they are members of the superclass)

What can we do with these variables? If a variable is of a particular
class (e.g. Vehicle) java only allows us use the methods and
variables defined for that class. This means that, even though the
object in our Vehicle variable is a Bicycle , we can only use the
methods in that object that are defined for Vehicle.
 What use are superclasses and inheritance?
 Saves programming time:
If you define methods and variables in a superclass, you don‟t have to
write them again in subclasses (the things we put into vehicle are
inherited in Bicycle, and hence in tandem and racer…)

More importantly: it can help make programs more adaptable. Why?

We can write code for doing something using a superclass (e.g. vehicle)
                                and then
Objects from any subclass of that superclass can be used in that code
(no matter how different they are). This is because the subclass objects
have all the variables and methods of the superclass (are members of the
superclass), and so can be used wherever the superclass is used.

This makes our code more adaptable and reusable.
       Code steering a vehicle to a target location
           (co-ords TargetX TargetY)
Vehicle V = new Bicycle();
int TargetX, targetY, dist_to, angle_to;
boolean at_target = false;
                                     Variables for distance to and
while (! at_target){                 angle to the target point
 angle_to = V.angle_to(targetX, targetY);
 if ( angle_to > 0) {V.turn_left();}
                                            Turn towards
 if ( angle_to < 0) {V.turn_right();}       the target
 dist_to =V.distance_to(targetX, targetY);
 if (dist_to != 0) {
   if (dist_to =< V.speed) {V.slow_down(); }
   if (dist_to > V.speed) {V.speed_up(); }
 }
 if (dist_to == 0) {                       If we‟re pointing at
   At_target = true;                       the target, start
   V.stop();                               moving towards it
 }
}
Polymorphism (generic programming)
In the above code, we guide a Bicycle to the target co-ords:
Vehicle V = new Bicycle();

However, we could put a tandem, airplane, car… into the
code and it would work unchanged.
Vehicle V = new Tandem();
Vehicle V = new Airplane();
Vehicle V = new Car();

Why will it work? Because those objects are all types of vehicle,
and so can go into a Vehicle variable, and be used in the code.

This is called polymorphism (literally “many shapes”: here we mean
“many types of things going into one piece of code”). This style of
programming is called “generic programming”.
              About polymorphism
The guidance code above uses the various methods defining vehicles
(turnleft(),turnright(),speedup()…)
 Because those methods are part of the definition of the class vehicle,
they can be used with the variable V, (which is of type vehicle,
and so has those methods).
Any object that is member of a subclass of vehicle:
    new Bicycle(); new Airplane(); new tandem();
can go into a variable of type vehicle.
 if vehicle methods (turn_left(),turn_right()) are called
for those objects, the right method is used for the right object:
•if V contains a new Bicycle() , then V.turn_left() will
change the handlebar_direction.
•if V contains a new airplane() , then V.turn_left() will
change the left and right flaps and the tail.
     Single inheritance+ instanceof
Each class in java can only extend one superclass:
class Airplane extends Vehicle {
class Airplane extends Vehicle, Weapon {                   won‟t work

We can find out if a given object is a member of a given
class by using instanceof
                                              And we can convert
  if (V instanceof Bicycle) {                 from a superclass to a
      Bicycle B = (Bicycle) V;                subclass using a cast
 }                                            (as we‟ve seen before)

The fact that each class can only extend one superclass is a bit of
a limitation when we‟re doing generic programming.
Java provides a more flexible structure, called an interface
           more flexible: interfaces
What sort of objects will fill the V Vehicle variable in the
„guidance‟ code above? They will all have methods:
   abstract    void   Turn_left();
   abstract    void   Turn_right();
   abstract    void   Speed_up();
   abstract    void   Slow_down();
and whatever other methods and variables are defined for Vehicle.
(such as num_seats, num_people etc.)
Our guidance code doesn‟t need to be limited to vehicles only; it
would be useful to be able to guide objects that don‟t necessarily
have to carry people, have seats…
In fact, for something to take part in the guidance code, it needs only
to have the methods turn_left turn_right speed_up and
slow_down. These are the only methods of the V Vehicle that are
actually used in that code.
We can define these methods as an interface for that code.
                 Interfaces in Java
An interface is a particular kind of class used as a variable
type in a different class or piece of code. All objects which that
code manipulates must implement the interface. The interface
describes how objects used by that code must behave.
An interface consists of a set of method declarations with no
code (like abstract methods). Classes which implement
an interface must give definitions for all those methods.

interface GuidableObject{              An interface specifies what is
  public void TurnLeft();
                                       required of an object for a
  public void TurnRight();
  public void speed_up();              particular piece of code to
  public void slow_down();             operate on that object. This
  public int curr_speed();             interface specifies what
  public int distance_to();            methods are required for an
  public int angle_to();
                                       object to be guidable to a target.
  public void Stop();
}
Now, if anything implements the GuidableObject interface,
it is saying that it is a guidable object, and so can be used in the
“guide to target” code:

class Vehicle implements GuidableObject{
class SmartBomb implements GuidableObject{
class Robot implements GuidableObject{

If a class implements an interface, that means it has all the
methods listed in the interface, and can thus take part in code
using that interface.

We can declare variables using an interface as the type:
GuidableObject V;         //GuidableObject is an interface

Any object that is a member of a class (or a subclass of a class)
that implements that interface, can go into that variable (because
it has the methods required for that interface)
     Guidance code with interface
int targetX, targetY;
boolean at_target = false;
GuidableObject V = new bicycle();
                   //or new Robot(), SmartBomb()…
while (! at_target){
int angle_to = V.angle_to(targetX, targetY);
if ( angle_to > 0) {V.turn_left();}
if ( angle_to < 0) {V.turn_right();}
int Dist_to =V.distance_to(targetX, targetY);
int speed = V.curr_speed();
if ((dist_to != 0) {
   if (dist_to =< speed) {V.slow_down(); }
   if (dist_to > speed) {V.speed_up(); }
   }
if (dist_to == 0) {
   At_target = true;     V.stop();
   }
}
   Classes, interfaces, & inheritance
Class inheritance in java is strict: each class extends only one
superclass, and inherits only from that class. Java does not allow
multiple inheritance: Statements like
class X extends OneClass,OtherClass                       are wrong.
For interfaces, the situation is different: a single class can implement
multiple interfaces. This statement is correct java syntax:
class X implements MyInterface,OtherInterface
(To implement an interface a class just provides the correct methods:
a single class can provide methods for a number of interfaces)
A class can simultaneously extend another class and implement a
number of interfaces:
 class X extends OneClass implements MyInterface etc.
is correct Java syntax.

				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:0
posted:7/9/2011
language:English
pages:21