Like Classes, They Introduce Types. Why Use Them? ..
The document describes abstract classes and provides an example of using an abstract Shape class to define subclasses for Circle and Rectangle shapes. The abstract Shape class declares an abstract area() method that is implemented in the subclasses to calculate each shape's area. An array of Shape references can then hold Circle and Rectangle objects and call the area() method polymorphically to calculate the total area of all shapes.
Download as PPT, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
22 views
Like Classes, They Introduce Types. Why Use Them? ..
The document describes abstract classes and provides an example of using an abstract Shape class to define subclasses for Circle and Rectangle shapes. The abstract Shape class declares an abstract area() method that is implemented in the subclasses to calculate each shape's area. An array of Shape references can then hold Circle and Rectangle objects and call the area() method polymorphically to calculate the total area of all shapes.
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 16
Abstract Classes
•Unlike classes, these cannot be instantiated.
•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();