Title: CS 162 Spring 2005
1CS 162 Spring 2005
2Another Form of Polymorphism
- Inheritance is a different type of Reuse
(polymorphism) than we have seen - Interfaces - Reuse of Concept (specifications,
descriptions) - Inheritance - Reuse of Code (Behavior, Methods,
Actual Code)
3Inheritance as Extension
- Inheritance is often described as Extension,
because when you inherit you get the behavior of
a parent class, and can extend or add data fields
or methods. - Class SavingsAccount extends BankAccount
-
-
4Polymorphic Assignment
- Just like with Interfaces, Inheritance brings
with it the polymorphic assignment. Can assign a
subclass to a superclass variable - BankAccount ac new SavingsAccount()
- Ac is "many faced", because it can hold any type
of BankAccount
5Inheritance
- Re-usable code, maintainable code
- Implemented in Java using classes with extends or
implements - Base (super) class / derived class
- Hierarchy of classes
- "parent", "grandparent", "ancestor", etc. (super)
- "child", "grandchild", "descendant", etc.
(derived) - transitivity
- Models the "is a kind of" relationship
- Other direction is a generalization of"
6(No Transcript)
7Some features of inheritance
- Derived classes can add new attributes and/or new
methods - Derived classes can override base class methods
- Every instantiation of a derived class is an
instanceof its own class and is an instanceof its
base class (including parent, grandparent, etc.)
8Relation to Polymorphism
- Suppose class Savings Account overrides method
interest originally defined in class
BankAccount - BankAccount ac new SavingsAccount()
- System.out.println(interest ac.interest())
- // will do method in SavingsAccount,
- // NOT the method in BankAccount
9Some rules of inheritance
- Derived classes may not remove attributes or
methods. - public base class methods may not be overridden
by private derived class methods. - Multiple inheritance is not supported in Java
- Base class can't "inherit" from derived class.
- protected attributes and methods in a base class
can be accessed only from the base class and its
derived classes ( actually the rule is more
complicated than that) - Every class automatically inherits from Object
- Primitive types are not objects ("wrappers"
required).
10Derived classes can
- Inherit method Don't supply a new implementation
of a method that exists in the base class - Override method Supply a different
implementation of a method that exists in the
base class - Add method Supply a new method that doesn't
exist in the base class
11Derived classes can
- Inherit field All fields from the superclass are
automatically inherited - Add field Supply a new field that doesn't exist
in the base class
Derived classes can not
Override field All fields from the base class
are automatically inherited
12(No Transcript)
13public class shape public double area() throws
RunTimeException throw new
RunTimeException( Area not defined for this
shape.)
14public class Circle extends Shape public
Circle( double rad ) radius rad
public double area( ) return
Math.PI radius radius public
double perimeter( ) return 2 Math.PI
radius public String toString(
) return "Circle " radius
private double radius
15public class Rectangle extends Shape public
Rectangle( double len, double wid )
length len width wid public
double area( ) return length width
public double perimeter( )
return 2 ( length width )
public String toString( ) return
"Rectangle " length " " width
public double getLength( ) return
length public double getWidth( )
return width private double
length private double width
16Using super
- public class Square extends Rectangle
- public Square( double side )
- super( side, side )
-
- // Note We could define area() for square as
- // public double area()
- //
- // return super.area()
- //
- public String toString( )
- return "Square " getLength( )
-
- public double diagonal()
- return Math.sqrt(2) super.getLength()
-
17public class ShapeDemo public static void
main( String args ) Shape a new
Circle( 2.0 ), new Rectangle(
1.0, 3.0 ), new Square( 2.0 )
System.out.println( "Total area "
totalArea(a) ) printAll(a) public
static double totalArea( Shape arr )
double total 0 for( int i 0 i lt
arr.length i ) if( arr i ! null )
total arri.area( ) return total
public static void printAll( Shape arr )
for( int i 0 i lt arr.length i )
System.out.println( arri.toString() )
18Using an interface
- public abstract class Shape implements Comparable
public double area() throws RunTimeException
throw new RunTimeException - (Area not defined for this
shape.) public int compareTo( Object
rhs ) Shape other (Shape) rhs double
diff area( ) - other.area( ) if( diff 0
) return 0 else if( diff lt 0 )
return -1 else return 1
19Application
- public class ShapeTest
- public static void main(String args)
- Circle c new Circle(2.5)
- Rectangle r new Rectangle(1.5, 3.5)
- System.out.print(The area of
c.toString()) - if(c.compareTo(r) 0)
- System.out.print( is equal to )
- else if (c.compareTo(r) 1)
- System.out.print( is greater than )
- else
- System.out.print( is less than )
- System.out.println( the area of r
.toString())
20Any class can prevent inheritance using final
- public final class Triangle extends Shape
- // etc.
-
21Converting Subclasses ? Superclasses
- Ok to convert subclass reference to superclass
reference - square s new square(10)rectangle r
sObject anObject s - Not OK to convert superclass reference to
subclass reference - double d r.diagonal() // ERROR
22Access Control Level
- public
- private
- protected (accessible by subclasses and package)
- package access (the default, no modifier)
23Recommended Access Levels
- Fields always private
- except public static final constants
- Methods public or private
- Classes public or package
- Don't use protected
- Beware of accidental package access (forgetting
public or private)
24Object The Cosmic Superclass
- All classes extend Object
- Most useful methods
- String toString()
- boolean equals(Object otherObject)
- Object clone()
25Overriding the equals method
equals tests for equal contents tests for
equal location Must cast the Object parameter
to subclass public class Rectangle public
boolean equals(Object otherObject) Rectangle
other (Rectangle)otherObject return (length
other.length) (width
other.width)
26equals Two Objects with same Contents
Rectangle length 3.5 width 1.7
rec1
Rectangle length 3.5 width 1.7
rec2
27 Two References to same Object
Rectangle length 3.5 width 1.7
rec1
rec2
28Questions?
- Read Chapter 12
- Now your chance to test your understanding - do
the anti quiz