Overriding
Look at
Computer class and Laptop class instance variables
Write a
toString method for Computer class
Will it
work for the Laptop class?
We have to write another toString
for the Laptop class, but wed like it to call the toString of the super class
Overloading
It is very
common to overload the constructor in a class
Polymorphism
Suppose we have in our client
using the Computer and Laptop classes this:
Computer[ ] labCom = new Computer[10];
//what
exactly happens in RAM wit this statement
for(i = 0;
i<10; i++)
{
System.out.println(Is the computer you want to record data for a laptop
or desktop?);
compType = in.next( );
// propmt for the for instance variables for all computers and save
input
if (compType.equals(Laptop)
// prompt for the extra
two items
Computer labComp[i] =
new LapTop( six arguments);
else Compute labComp[i] = new Computer( four
args);
The type of an object referenced is
determined by the constructor;
The type of the reference variable
may or may not be the same as the object referenced; if it is not the same,
it is the type of a superclass
Abstract
methods and classes
Sometimes you want to require that
all subclasses override a method
Suppose we want to keep track of a
bunch of shapes, but we wont know much about the shapes until the user enters
the data
We do know that we will want to find
the perimeter and area of all the shapes
We design a class hierarchy to help
us keep track of this data
The superclass will be Shapes, and
will require all its subclasses have methods to calculate area and perimeter
We can not know how to implement the
methods for the superclass so we declare the methods to be abstract, and write
only the headers
An abstract method is one that has
not body i.e. not implemented
public abstract class Shape
{
public abstract double area ( ); // must return
the area
public abstract double perimeter ( );
} if a class has even one abstract method, the
class is abstract
Now we write the subclasses, which
must implement the abstract methods
public class Circle
{ private double
radius;
public
Circle( ) { radius = 0.0;}
public Circle (
double r) { radius = r; }
public double
area( ) { return PI * r * r; }
public
double perimeter( ) { return PI*2*r; }
}
Now the client of the classes can make an array of Shapes