inheritance by dandanhuanghuang

VIEWS: 7 PAGES: 24

									Inheritance

Chapter 9
 Inheritance
                                       Superclass

subclass of Animal
superclass of dog and cat




                            Subclass
          Superclass
          has its own
           fields and
            methods
                            Mammal
                            private final int nbrlegs = 4;
                            private final stuff covering = FUR;
Subclass inherits           -----------
                                                                           Subclass
all of superclass           Mammal() { // constructor}
                                                                          has its own
    fields and              FeedsYoung() { nurses();}
                                                                           fields and
  methods and               GivesBirth() { liveyoung(); }
                                                                            methods
adds some of its
        own
                    Dog                         Cat
                    // fields for dogs          // fields for cats
                    -------                     --------
                    Dog() {// constructor }     Cat() { // constructor}
                    public void wagstail()      public void ignore()
                    {}                          {}
Inheritance Advantages
 One superclass for lots of subclasses
 Saves code rewriting for client
 Save code rewriting within class


   Note: There does not have to be an object
    of a superclass – there are no “animal”
    objects, but there may be: (triangle,
    isosceles triangle, right angle isosceles
    triangle).
Shapes Example
   Circle has:
     color,   xPosition, yPosition, Diameter
   Triangle has:
     color,   xPosition, yPosition, length, height


   Make a parent: Shape
        Shape
        int xPosition;
        int yPosition;
        String Color;
        -------
        // constructor and methods



Circle               Square           Triangle
int diameter;        int length;      int height, length;
-----                ----             ---
Circle methods       Square methods   Triangle methods
                    Shape
                    int xPosition;
                    int yPosition;
                    String Color;
                    -------
                    // constructor and methods
                    moveVertical(int n)
                    all other methods


Circle                              Triangle
int diameter;                       int height, length;
-----                               ---
Circle methods                      Triangle methods
draw( )                             draw( )
changeSize(int newSize)             changeSize(int newH, int newL)
              Assignment
 Circle c = new Circle ( );
 Shape s = new Shape( );
 s = c; // ok, a circle IS a shape
 c = s; // NOT ok. A shape might be
  something other than a Circle
                 Assignment
 a = b; // all b are a
 b must the same class as a, or a subclass
  of a
 b IS-A a (note: backwards of assignment
  order)
     dog  is a mammal
     Circle is a Shape
   does NOT work for a IS-A b (same order
    as assignment)
     mammal   is not necessarily a dog
                 Objects & methods
                       obj.method( )
   method must be in obj class or a parent class
       Circle c = new Circle();
       c.draw( ); // ok. draw is a Circle method
       c.changeColor("green"); // ok. changeColor is a Shape method

       Shape s;
       s.draw( ) ; // NOT ok. draw is a method of its children
       s.changeColor("green"); // ok. changeColor is a Shape method

   If method is in the super class, ok. that's the point of
    inheritance.
Subtyping
   Object variables in Java can hold objects
    of the declared type, or of subtypes of the
    declared type.

   Big advantage in many applications
Subtyping
Shape s1 = new Shape( ); // ok
Circle c = new Circle( ); // ok
Triangle t = new Triangle( ); // ok
Shape s2 = new Circle( ); //ok. all circles are shapes
Circle c2 = new Shape( ); // NOT ok. not all shapes
         LHS must be same level
                                // are circles
--------- or higher than RHS
c.findCircumference ( ); // ok if method exists
                                                        be
s2.findCircumference( ); // NOT ok object mustthansame level
                                               or lower    method
((Circle)s2).findCircumference( ); // ok s2 is a Circle

          Casting
Casting
   Turn one type into another (when it’s ok)
   double sphere = 4 / 3 * Math.PI * r * r * r;
                      4/3=1

   fix:
double sphere = (double) 4 / 3 * Math.PI * r * r * r;
                  Creates a new
                  value, 4.0
                  (double) from 4
   4.0 / 3 = double/ int = double / double = 1.333…
                      3 is automatically coerced into a double.
                      Casting does it explicitly, and is programmer
                      controlled
Casting and Inheritance Practice
A. Ok B. Not OK
1.    int y=3; double g=3;
2.    int x = (double) y;
3.    double z = (int) g;
4.    MyShape s = new Circle( );
5.     Circle c = new Circle( );
6.     s.moveVertical(10);
7.     c.moveVertical(10);   }        critical
        c.findCircumference( );
8.
9.      s.findCircumference( );  }   Also critical
10.     ((Circle) s).findCircumference( );
Methods and Inheritance
   ok to call method in the class or in a superclass
   NOT ok to call method of a subclass
   To do that, object must be cast to the class
    where method appears
     ((Circle) s).draw(         ); // no syntax error
        // ok if s is a Circle
   Will get a run-time error if object is NOT the
    subclass
     Shape   s = new Square( ) ; // ok
     ((Circle) s).draw( ); // ok in syntax. run time error
Mammal
private final int nbrlegs = 4;
private final stuff covering = FUR;                  Practice
-----------
Mammal() { // constructor}            A. OK B. NOT OK
FeedsYoung() { nurses();}
GivesBirth() { liveyoung(); }


                                        1. Dog d = new Mammal();
 Dog
 // fields for dogs
                                        2. Mammal m = new Dog( );
 -------
 Dog() {// constructor }                3. StBernard s = new Dog();
 public void wagstail() { }
                                        4. m.FeedsYoung( );
                                        5. d.slobbers();
   StBernard
   // fields for St. Bernards           6. s.wagstail();
   ------
   StBernard { /* constructor*/}        7. s.FeedsYoung();
   public void slobbers() { }
Practice: A. OK B. Not OK
Assume we have 4 classes: Person, Teacher, Student and
    PhDStudent. Teacher and Student are both subclasses of
    Person. PhDStudent is a subclass of Student. Which of the
    following are legal?
1.  Person p1 = new Student( );
2.  Person p2 = new PhDStudent( );
3.  PhDStudent phd1 = new Student ( );
4.  Teacher t1 = new Person( );
5.  Student s1 = new PhDStudent( );

6.    s1 = p1;
7.    s1 = p2;
8.    p1 = s1;
9.    t1 = s1;
10.   s1 = phd1;
11.   phd1 = s1;
Practice 2: do on the board
8.17 Look at the code below. You have four classes (O, X, T and M)
    and a variable of each of these.
O o;
X x;
T t;
M m;
The following assignments are all legal:
m = t;
m = x;
o = t;
The following assignment are all illegal:
o = m;
o = x;
x = o;
What can you say about the relationships of these classes?
Inheritance Syntax
public class Superclass
{
}

public class Subclass extends Superclass
{
}
Inheritance code for Person
  public class Person
                                        parent classes
  {                                    are no different
  private String name;                from any classes
                                      we have written.

  public Person() // constructor
   { // do constructor-like stuff }

  public Person(String n)
  { name = n; }

  public void getName( )
  { return name; }
  // other methods
  }
inheritance is
 implemented
with “extends”       Code for Student
          public class Student extends Person
          { private String school;

            public Student( ) {                    Must call parent
                                               constructor as first line
             super( );                         of subclass constructor
             school = "Christopher Newport University";        }

          public Student(String name, String school) {
           super(name);
           this.school = school; }

          public void getSchool( ) {
             return school; }
          }
Superclass constructor call
  Subclass constructors must always
   contain a 'super' call.
  If none is written, the compiler inserts
   one (without parameters)
      works only, if the superclass has a
       constructor without parameters
    Must be the first statement in the
     subclass constructor.
    Client using Person and Student
    A. OK; B. NOT ok
public class MyClient
{
  Person p = new Person( );
  Student s = new Student( );
  Person r = new Student( );

    public MyClient( )
    {
      p.getName( ); // 1
      s.getSchool( ); // 2
      s.getName( ); // 3
      r.getSchool( ); // 4
}
Inheritance: what do we know?
 extends // used in subclass
 superclass has no indication inheritance is
  being used
 super() // calls constructor of superclass
     must   be first statement of subclass

								
To top