02 console class creation

30
Lab C# Shape Class Console App Brian Lai HKCT 2015 - 2016 1

Upload: allenchow

Post on 11-Apr-2016

215 views

Category:

Documents


0 download

DESCRIPTION

Class Creation Demo

TRANSCRIPT

Lab C# Shape Class Console App

Brian Lai HKCT 2015 - 2016

1

The Design: Top Down Approach

2

1. We start with the Main program design on what to test. 2. Then, design class Shape on what methods in common. 3. Finally, design concrete classes: Circle and Rectangle, to support the class Shape.

The Idea: Shapes are extendable to classes such as Triangle, Oval, Text, Polygon

3

The Main Program

4

The Class Shape

5

Class Circle

6

Class Rectangle

7

The Implementation: Bottom up Approach

8

1. We test out the concrete classes: Circle and Rectangle. 2. Then, test the abstract class: Shape. 3. Main program is the test driver.

To Create a Class Right Click on the Project Title

9

Then select Add, Class

10

Change Class1.cs to your Class Name

11

Rename Example: MyCircle.cs

12

A Class MyCircle.cs file created

13

Add Code to MyCircle Class

14

Create MyRectangle Class

15

Add Code to MyRectangle Class

16

Having MyCircle and MyRectacgle classes defined.

Time to add code to the main

program.

17

Add code to the Main Program

18

The Main Program does not Work? Why?

19

Answer: Cannot determine the circle object at compile time.

Run time allocation

Error !!!

The Fix: change run time to compile time allocation

20

New the circle object at compile time.

Add rectangle object for testing

21

Add Abstract class MyShape

22

Add Code to MyShape: “virtual” is the key word

23

Update class MyCircle: “override” is the key word

24

Update class MyRectangle: override

25

Main Program I: use of shapes array

26

Up cast MyCircle And MyRectangle objects To shape.

Main Program II: output shapes array

27

Sample Output

28

How to add Triangle, Oval, Text, Polygon to the Design and the program

29

Triangle

Polygon

End of Polymorphism Console App

30