Download presentation
Presentation is loading. Please wait.
Published byNoah Lamb Modified over 8 years ago
1
INTRODUCTION TO CLASSES & OBJECTS CREATING CLASSES USING C#
2
OBJECTS VS CLASSES Classes are abstract definitions of what an object can do and values it can hold Classes are a mix of code and data An object is an instance of a class Classes are general and Objects are specific examples
3
DATA HIDING Class data is private Protected from unsafe manipulation Modified only by class specific methods Methods may be public or private Private methods for internal class use only Public methods are defined interface to the class’ data
4
DECLARING THE DATA class Die { private int _sides; private int _value; Variables are declared private Variable names start with underscore (_) to highlight that they are private (optional) Variables declared as private
5
CONSTRUCTORS Constructors are methods in a class that set the initial state of an object Constructors: Are public Have the same name as the class Do not have a specified type Initialize private values in a class
6
SAMPLE CONSTRUCTORS public Die() { _sides = 6; ChangeValue(); } public Die(int sides) { _sides = sides; ChangeValue(); } Default constructor No parameter Non default constructor Parameter(s) Default value for number of sides Number of sides set to value passed to the constructor
7
ACCESSING THE DATA Class data should be accessed using methods or properties Changes to data should be validated carefully inside the class if allowed at all Some data should not be allowed to be changed after the constructor
8
CHANGING DATA - METHOD private void ChangeValue() { _value = r.Next(0, _sides) + 1; } Declared private Used only in the class Code to set value is “hidden”
9
RETURNING DATA - METHOD public int Roll() { ChangeValue(); return _value; } _value changed in a private method _value returned by method not by direct access
10
GETTING/SETTING DATA - PROPERTY public int Value { get { return _value; } set { if (value > 0 && value < _sides+1) _value = value; } } _value returned by method not by direct access _value set in a protected fashion
11
DECLARING AN OBJECT Die dSix = new Die(); Die d12 = new Die(12); Default constructor Six sides are default Non default specifies the number of sides
12
REVIEW An instance of a class is an object One or more constructors to set initial values Constructors have the same name as the class Access to data is limited and protected
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.