Download Object-Oriented Programming with Classes and Dice: Understanding State and Behavior and more Slides Information Security and Markup Languages in PDF only on Docsity!
Classes
Methods and Properties
Introduction to Classes and Objects
- In object-oriented programming terminology, a class is defined
as a kind of programmer-defined type
- From the natural language definition of the word “class”:
- Collection of members that share certain attributes and functionality
- Likewise classes in object-oriented programming
- In object oriented programming languages (like C#, Java)
classes are used to combine everything for a concept (like
date)
- Data ( state / attributes ) (e.g. date day, month, year)
- Methods (behavior / tasks) (e.g. display date, increment date)
An Overview of Object Oriented (OO)
Programming
- An example without OO programming - Calendar display program
- needs several utility functions/methods
- leap year check
- day of week function
- …
day
day of week
month
MonthName leap year
Data year
Functions
...
Is this structure complex?
- for some yes, for some no
An Overview of Object Oriented (OO)
Programming
- OO version - Calendar display program
- Date concept is developed as a class
- data and methods combined together from the point of view of programmer
Did you like this?
- for some yes, for some no OO approach is more suitable for a human being
- human cognition is mostly based on objects
Data (day, month, year) Methods Day of the week Month name …
Introduction to Classes and Objects
- We define variables of types (like int, double). Similarly,
we define objects of classes
- an object is a member of a class
- Why classes and objects? In other words, why object-
oriented programming?
- It gives programmers the ability to write programs using off-the- shelf components without dealing with the complexity of those components
- Saves time and effort
- Objects are how real-world entities are represented.
- You may design and implement, and later use your own
classes, but we will start with using other-programmers-
defined classes
- Examples: we used the Console class
- this is what a programmer generally does
How to Use Classes?
- The behavior of a class is defined by its
methods by which objects of that class are
manipulated
- You should know about the methods and what they
do
- name of the method
- parameters and parameter types
- return type
- functionality
- You don’t need to know how the method is
implemented
- analogy: you can add two int variables using +, but you
don’t need to know how computer really adds
- more analogy: you can drive cars, but you don’t need
to know how the fuel injection works
The class Dice
- Computer simulated dice
- not real dice, but have the same functionality
- random number between 1 and “number of sides”
- in this class, we can have dice objects with any number of sides
State
number of sides roll count
Methods
Dice(int sides) // constructor – constructs a die with given number of sides int Roll() // return the random roll int NumSides() // how many sides int NumRolls() // # of times this die rolled
- Dice objects will work as pseudo-random number generator Random class from .NET library
Using the class Dice
Console.WriteLine("Rolling {0} sided die.", cube.NumSides()); Console.WriteLine(cube.Roll()); Console.WriteLine(cube.Roll()); Console.WriteLine("Rolled {0} times.", cube.NumRolls());
methods
Dice cube = new Dice(6); // construct six-sided die
Dice dodeca = new Dice(12);// construct twelve-sided die
See UseDice.cs for full program
constructor
State and Behavior
Behavior of a class is what a class does
described in verbs babies eat, cry dice are rolled In OO programming terminology, behavior is defined by public methods
for Dice class, methods are the Dice constructor,
NumRolls(), NumSides() and Roll()
State of a class depends on physical properties
cars have four wheels, different colors dice have a number of sides In OO programming, State is defined by private data also called member data , instance variables , or data fields for Dice class, mySides and myRollCount (see Dice.cs)
Objects
- An object is an instance of a class
- When created, in memory a set of private data
members are allocated and initialized according to
the constructor method
- In other words, each object has a different state
- However, objects share method implementations
- The same function name is used on all objects of the same class
- When a method is called on an object, that object’s
private data members are accessed and/or modified
Anatomy of the Dice class
- The class Dice
- Objects: 6-sided dice, 32-sided dice, one-sided dice
- Methods: Roll(), NumSides(), NumRolls()
- A Dice object has state and behavior
- Each object has its own state, just like each int has its own value - Number of times rolled, number of sides
- All objects in a class share method implementations,
but access their own state
- How to respond to NumRolls()? Return my own # of rolls
What to know?
Client programmer (programmer who uses the classes) needs
to know the interface
public methods and constructors parameters, how they behave does not need to know private data does not need to know how the methods are implemented
From interface to use, the class Dice
static void Main(string[] args) { Dice cube = new Dice(6); Dice dodeca = new Dice(12);
Console.WriteLine(cube.Roll());
Objects constructed
0
myRollCount mySides 6
cube
0
myRollCount mySides 12
dodeca
Method invoked
1
myRollCount mySides 6
cube
Let’s look at the Dice.cs
• Definition and implementation of the Dice class
Understanding Class
Implementations
- Private data members are global such that they are
accessible by all class member functions
- e.g. in the implementation of Roll function, mySides and myRollCount are not defined, but used
Understanding Class
Implementations
- Constructors should assign values to each instance
variable
- this is what construction is
- not a rule, but a general programming style
- All data should be private
- Provide propertied or methods as needed
Random class
- Objects of class Random can produce random byte, int and double values.
- Method Next of class Random generates a random int value.
- The values returned by Next are actually pseudorandom numbers —a sequence of values produced by a complex mathematical calculation.
- The calculation uses the current time of day to seed the random- number generator.
- If you provide Next with two int arguments, it returns a value from the first argument’s value up to, but not including, the second argument’s value.
- The calculation that produces the pseudorandom numbers uses the time of day as a seed value to change the sequence’s starting point.
- You can pass a seed value to the Random object’s constructor.
- Given the same seed value, the Random object will produce the same sequence of random numbers. Docsity.com
Access Modifiers
class Dice
{
private int myRollCount; // # times die rolled private int mySides; // # sides on die
public Dice(int sides)
{
}
public int Roll()
{
}
}
- Default is private. (if there is no access modifier) Docsity.com
Access modifiers
public
Methods and Constructors as seen by programmer Programmer can use the methods and properties defined in the public section only
private
Mostly the data part of the class Necessary for internal implementation of class Not accessible by programmer
- protected
- we will see this in inheritance
- internal
- Accessible only by methods in the defining assembly
- protected internal
- we will see this in inheritance
Member Data (instance
variables)
class Dice
{
private int myRollCount; private int mySides;
}
- Will the following code compile?
Dice cube = new Dice(6); Console.WriteLine("Number of sides: {0}", cube.mySides);
Console.WriteLine("Number of sides: {0}",
cube.NumSides());
- Hiding data (encapsulation): why?
- you can drive cars, but you don’t need to know how the fuel injection works
- when the car’s fuel injection changes, you can still drive that new car
Properties
private int myRollCount; // # times die rolled
// property to get and set the number of sides
public int NumRolls
{
get { return myRollCount; } // end get set { myRollCount = value; } // end set
} // end property NumRolls
- Does get makes sense? How about set?
Properties
private int mySides; // # sides on die
// property to get and set the number of sides
public int NumSides
{
get { return mySides; } // end get set { mySides = value; } // end set
} // end property NumSides
Console.WriteLine("Number of sides: {0}", cube.NumSides);
- Does get makes sense? How about set?
Autoimplemented Properties
// property to get and set the roll count public int NumRolls { get; private set; }
// property to get and set the number of sides
public int NumSides { get; set; }
public Dice(int sides)
{
NumRolls = 0; NumSides = sides;
}
Methods
- The best way to develop and maintain a large application is to
construct it from small, simple pieces divide and conquer
- Methods allow you to modularize an application by
separating its tasks into reusable units.
- Reuse the Framework Library, do not reinvent the wheel
- Divide your application into meaningful methods such that it
is easier to debug and maintain.
- Methods == Worker analogy:
Methods syntax
access_modifier return_type func_name(parameter list) { statement_1; … statement_n; return return_type; } (type param 1 , type2 param 2 , …, type paramn)
public, private
Examples:
- public int Roll()
- public Dice (int sides)
- public static void Main (string[] args)