• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Classes1
 

Classes1

on

  • 506 views

 

Statistics

Views

Total Views
506
Views on SlideShare
506
Embed Views
0

Actions

Likes
0
Downloads
9
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Classes1 Classes1 Presentation Transcript

    • 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 year Data 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());
      Dice cube = new Dice(6); // construct six-sided die Dice dodeca = new Dice( 12 ); // construct twelve-sided die See UseDice.cs for full program methods 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 me thod 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
          • p arameters, 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 my Sides 6 cube 0 myRollCount my Sides 12 dodeca Method invoked 1 myRollCount my Sides 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 function s
        • 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.
    • 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)
    • 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 );
      • How to fix this?
      • 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 param n )
      • public, private
      • Examples:
      • public int Roll ()
      • public Dice ( int sides )
      • public static void Main ( string[] args )
    • Methods syntax (cont’d)
      • There are three ways to return control to the statement that calls a method .
        • Reaching the end of the method.
        • A return statement without a value.
        • A return statement with a value.
      • There could be more than one return in a method.
      • At least one return is required in a non-void method.
    • Method Overloading
      • void DoSomething( int num1, int num2 );
      • void DoSomething( int num1, int num2, int num3 );
      • void DoSomething( float num1, float num2 );
      • void DoSomething( double num1, double num2 );
      • The compiler distinguishes overloaded methods by their signature —a combination of the method’s name and the number, types and order of its parameters.
      • Method calls cannot be distinguished by return type  compile error
        • int SquareRoot( int num );
        • double SquareRoot( int num );
      • Constructor can be overloaded too.
    • Scope of Variables
      • The basic scope rules are as follows:
        • The scope of a parameter declaration is the body of the method in which the declaration appears.
        • The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration.
        • The scope of a non-static method, property or field of a class is the entire body of the class.
      • If a local variable or parameter in a method has the same name as a field, the field is hidden until the block terminates
      • Let’s see an example: scope.cs
    • Static Methods
      • public class ScopeTest
      • {
      • public static void Main(string[] args)
      • }
      • public static class Math
      • {
      • public static int Max(int val1, int val2);
      • public static int Min(int val1, int val2);
      • }
      • You do not need to create an object in memory to use the method, you simply use the class’s name to call the method
      • Other methods of the class cannot be called from a static method, only static methods can be called from other static methods
    • Math class example ( maximum3.cs )
      • Let’s write a program that finds the maximum of 3 numbers
        • Randomly generate the numbers
        • Then let’s use the Math class to find the maximum