Docsity

Creating a Circle Class in C#: Encapsulation, Attributes, Methods, and Properties, Slides of Computer Science

Partial preview of the text

Download Creating a Circle Class in C#: Encapsulation, Attributes, Methods, and Properties and more Slides Computer Science in PDF only on Docsity!

Chapter 8 – Classes

How to create your own classes

Key Concepts or Terminology 

Encapsulation (wrapping together) 

Attributes (data) 

Methods (behavior) 

Information hiding 

Class 

Instantiation

Describing a Circle Suppose that we wish to create a “type” Circle

that represents an arbitrary circle in theplane. What does it take to describe a circle?

A pointA radius What constitutes a point?

An x – coordinateA y – coordinate

So three pieces of information are needed for a

circle. It can be represented by three doublenumbers which represent the x-coordinate,the y-coordinate and the radius. Our classwill need these three data items.

Developing a circle. A starting point has been established on our

web page for the class. We will develop thisclass to the point that we can: 

declare a circle; 

assign or set the values of a circle; 

show information about the circle;

Throughout the development we need to pay

attention to encapsulation and protection. Forexample, would you ever want a circle with anegative radius?

Add another feature Suppose we are doing geometry with circles,

and we need to know whether or not twocircles (already established) intersect eachother. We will set up a boolean valued method that

will let one object call the method and test itwith another object.

Properties Properties can be added to any class. They

will have names and represent attributesassociated with an object in the class. Properties can also be used to retrieve data

from an object or set data in an object.

Property syntax public

return-type property-name

{

get{

code to get information

} set{

code to set information

} }

Write a property that allows you to get andset the radius of an instantiated circle. We will add this to our Circle class. In the set

portion, you will see some similarities with theSetCircle method. When a property is used to set a value, as in

C1.Radius = 3.2; The value of the expression on the right of the

= is computed and is represented by thereserved word

value

in the property definition.

You do some: Do the following one at a time and test each by

adding new lines of code in Main( )

Write a property that will set and get the x –coordinate.

Write a property that will set and get the y –coordinate.

Write a property that will return thecircumference of a circle.