您的位置:寻梦网首页编程乐园Java天地Core JavaJava Lecture Notes

Introduction

Content

Apply

Reflect

Extend

previous.gif
 (3087 bytes)

next.gif
 (2959 bytes)


Content Index

Content Page # 3

Introduction to inheritance

Inheritance is a key feature of object-oriented programming It embodies the idea that one thing is `like' (or a `type of') another thing. Inheritance is implemented in Java using the extends and implements mechanisms.

Here is a simple example. Suppose we are writing a computer program that allows the user to draw diagrams. It understands rectangles, circles, lines and text. We could write sections of program to handle each of these shapes, but if we did this we would soon find that we were writing the same program lines over and over again.

Why? Because all these shapes have a lot in common. All have one or more lines with a particular thickness and colour. All can be filled in with, perhaps, a different colour. All have a particular position on the screen, and so on. However, there are also differences between the different shapes. For example, the idea of `font' (typeface) is meaningful for text, but has no meaning for a line or circle.

The way inheritance works is that we define a class (perhaps called Shape) that contains all the program instructions. Then we define classes for each of the other shapes, which contain only the instructions that are necessary for that particular shape. So in the class `Text' (for example) that handles the drawing of text, we would include instructions for processing different typefaces.

Back to top

basicline.gif (169 bytes)

RITSEC - Global Campus
Copyright ?1999 RITSEC- Middlesex University. All rights reserved.
webmaster@globalcampus.com.eg