Docsity

Abstract Classes and Abstract Methods in Object-Oriented Programming II - Prof. Nelson Pad, Study notes of Computer Science

Partial preview of the text

Download Abstract Classes and Abstract Methods in Object-Oriented Programming II - Prof. Nelson Pad and more Study notes Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

Abstract Classes

Department of Computer Science

University of Maryland, College Park

Modifier – Abstract

Description

Represents generic concept Just a placeholder Leave lower-level details to subclass

Applied to

Methods Classes

Example

abstract class Foo { // abstract class abstract void bar( ) { … } // abstract method

Motivating Example – Shapes

Implementation

Picture consists of array shapes of type Shape[ ] To draw the picture, invoke drawMe( ) for all shapes Shape[ ] shapes = new Shape[…]; shapes[0] = new Circle( … ); shapes[1] = new Rectangle( … ); … for ( int i = 0; i < shapes.length; i++ ) shapes[i].drawMe( ); Store the shapes to be drawn in an array. Draws all the shapes. Each call invokes drawMe for the specific shape. Heap: shapes [0] [1] [2] … (a Circle object) (a Rectangle object) …

Motivating Example – Shapes

Problem

Shape object does not represent a specific shape Since Shape is just a superclass How to implement Shape’s drawMe( ) method? public class Shape { void drawMe( ) { … } // generic drawing method }

Abstract Method

Behaves much like method in interface

Give a signature, but no body

Includes modifier abstract in method signature

Class descendents provide the implementation

Abstract methods cannot be final

Since must be overridden by descendent class Final would prevent this

Abstract Class

Required if class contains any abstract method

Includes modifier abstract in the class heading

public abstract class Shape { … }

An abstract class is incomplete

Cannot be created using “new” Shape s = new Shape( … ); // Illegal! But can create concrete shapes (Circle, Rectangle) and assign them to variables of type Shape Shape s = new Circle( … );

Abstract – Summary

Abstract methods

Method that contains no body Subclass provides actual implementation

Abstract classes

Required if any method in class is abstract Can contain non-abstract methods Can be partial description of class