•Like classes, they introduce types. Like classes, they introduce types. Why use them? Why use them? • Because there is a set of common features and implementation for all derived classes but...... • We want to prevent users from handling objects that are too generic • We cannot give a full implementation for the class Problem:
Students are either undergraduate, PhD or MsC
We want to guarantee that nobody creates a Student object. The application always creates a specific kind of Student.
The solution: Declare Student as abstract.
Why have the Student class in the first place?
A common implementation of common aspects of all students. (e.g. setLogin and and getLogin ()) A place holder in my hierarchy that corresponds to a significant concept in my problem domain To handle all students independently of their subclass using type Student and polymorphism. public abstract class Shape { public abstract double area(); } class Circle extends Shape { double r; public Circle() { r = 1.0; } public Circle(double r) { this.r = r; } public double area() { return 3.1459 * r * r; } } class Rectangle extends Shape {double w, h; public Rectangle() { w = 0.0; h = 0.0; } public Rectangle(double w, double h) { this.w = w; this.h = h; } public double area() { return w * h; } } In main method Shape[] shapes = new Shape[3]; // Create an array to hold shapes. shapes[0] = new Circle(2.0); // Fill in the array... shapes[1] = new Rectangle(1.0, 3.0); shapes[2] = new Rectangle(4.0, 2.0); double total_area = 0; for(int i = 0; i < shapes.length; i++) total_area += shapes[i].area();