Chapter 9 Using Classes and Objects PDF

Summary

This document is lecture notes on C#. It covers multiple concepts of C#, including classes, objects and their properties. It provides practical examples using the C# programming language.

Full Transcript

COIS1020H: Programming for Computing Systems Chapter 9 Using Classes and Objects Understanding Class Concepts Classes are the basic building blocks of Object- Oriented programming Two Types of classes – Classes that are only application programs with a Main...

COIS1020H: Programming for Computing Systems Chapter 9 Using Classes and Objects Understanding Class Concepts Classes are the basic building blocks of Object- Oriented programming Two Types of classes – Classes that are only application programs with a Main() method (usually declared as static) – Classes from which you instantiate objects Can contain a Main() method, but it is not typical An object is an instantiation of a class 2 Understanding Class Concepts (cont'd.) Instance variables (also called fields) – Data components of a class State – Set of contents of an object’s instance variables Instance methods – Methods associated with objects – Every instance of the class has the same methods Class client or class user – Program or class that instantiates objects of another prewritten class (such as Console) 3 Creating a Class from Which Objects Can Be Instantiated Class header or class definition parts – An optional access modifier – The keyword class – Any legal identifier for the name of your class Class access modifiers – public – protected – internal – private 4 Creating a Class from Which Objects Can Be Instantiated (cont'd.) public class Employee { // Instance variables and methods go here } - Better to use a modifier as default is internal 5 Creating Instance Variables and Methods When creating a class, define both its fields and its methods Field access modifiers – new, public, protected, internal, private, static, readonly, and volatile Most class fields are nonstatic and private – Provides the highest level of security 6 Creating Instance Variables and Methods (cont'd.) Using private fields within classes is an example of information hiding Most class methods are public private data / public method arrangement – Allows you to control outside access to your data Like using a gas gauge to “see” the level of the gas – The private data fields are manipulated by well- defined (and programmer-defined) interfaces provided by the public methods 7 Creating Instance Variables and Methods (cont'd.) public class Employee - Better to use a modifier as default is internal { private int idNumber; public void WelcomeMessage() { Console.WriteLine(“Welcome from Employee #{0}”, idNumber); Console.WriteLine(“How can I help you?”); } } Employee class with idNumber field and WelcomeMessage()method Notice how the method has access to the idNumber field without having to pass the information as a parameter – instance methods have direct access to instance variables 8 Creating Objects Declaring a class does not create any actual objects – Just an abstraction (like a method until it is invoked) Two-step process to create an object – Supply a type and an identifier Employee bob; – Create the object, which allocates memory for it bob = new Employee(); Reference type – Identifiers for objects are references to their memory addresses 9 Creating Objects (cont'd.) using System; public static class CreateEmployee Invoking constructor { When you create an object, public static void Main() you call its constructor { Employee() is a method call Employee myAssistant = new Employee(); myAssistant.WelcomeMessage(); Console.ReadLine(); } Invoking an object’s method } 10 Understanding Constructors Constructor – Method that instantiates an object Default constructor – Automatically supplied constructor without parameters – The only time that C# provides a default constructor is when there are no programmer-defined constructors Default value of the object – The value of an object initialized with a default constructor Numeric fields are set to 0 Character fields are set to ‘\0’ Boolean fields are set to false References (strings and objects) are set to null 11 Overloading Constructors C# automatically provides a default constructor – Until you provide your own constructor Constructors can be overloaded – You can write as many constructors as you want As long as their argument lists do not cause ambiguity Chooses constructor based on the signature 12 Passing Parameters to Constructors You can create a constructor that receives arguments Using the constructor Employee partTimeWorker = new Employee(12.50); 13 Overloading Constructors (cont'd.) public class Employee { private int idNumber; private double salary; public Employee() { IdNumber = 999; 1 Salary = 0; } public Employee(int empId) { IdNumber = empId; 2 Salary = 0; } public Employee(int empId, double sal) { IdNumber = empId; 3 Salary = sal; } public Employee(char code) { IdNumber = 111; 4 Salary = 100000; } } 14 Overloading Constructors (cont'd.) using System; public static class CreateSomeEmployees { 999 $0.00 public static void Main() 234 $0.00 { 111 $100,000.00 Employee aWorker = new Employee(); Employee anotherWorker = new Employee(234); Employee theBoss = new Employee('A'); Console.WriteLine("{0} {1:C}", aWorker.IdNumber, aWorker.Salary); Console.WriteLine("{0} {1:C}", anotherWorker.IdNumber, anotherWorker.Salary); Console.WriteLine("{0} {1:C}", theBoss.IdNumber, theBoss.Salary); Console.ReadLine(); } } 16 Passing Objects to Methods You can pass objects to methods – Just as you can with simple data types using System; First employee's message public class CreateEmployee Welcome from Employee #0 { How can I help you? public static void Main() { Second employee's message Employee aWorker = new Employee(); Welcome from Employee #0 Employee bWorker = new Employee(); How can I help you? DisplayMessage("First", aWorker); DisplayMessage("Second", bWorker); } public static void DisplayMessage(string mess, Employee emp) { Console.WriteLine("\n{0} employee's message", mess); emp.WelcomeMessage(); } } 17 Accessor and Mutator Methods Because of the concept of data hiding, fields in a class are private. The methods that retrieve the data of fields are called accessors. – Each field that the programmer wishes to be viewed by other classes needs an accessor. The methods that modify the data of fields are called mutators. – Each field that the programmer wishes to be modified by other classes needs a mutator. Properties C# has an alternative to using accessor and mutator methods, called properties. Properties allow us to modify and access private data members like accessor and mutator methods without using public methods. Creating Properties Property – A member of a class that provides access to a field of a class (very helpful for private fields) – Defines how fields will be set and retrieved Properties have accessors – set accessors for setting an object’s fields setters (also called mutators) – get accessors for retrieving the stored values getters (or just accessors) Read-only property – Has only a get accessor 20 Properties Example public double Length { get { return length; } set { length = value; } } Properties key words get, set and value. The get and set blocks replace the function of the accessor and mutator methods. The get and set blocks use a variable named value – Implicit Parameter: one that is undeclared and that gets its value automatically – The get block uses the value to return the actual value of the instance field. – The set block uses the value to set the value of the instance field. Creating Properties (cont'd.) public class Employee { private int idNumber; public int IdNumber Notice { get { return idNumber; } set { idNumber = value; } } public void WelcomeMessage() { Console.WriteLine("Welcome from Employee #{0}", IdNumber); Console.WriteLine("How can I help you?"); } } 23 Creating Properties (cont'd.) using System; public class UseEmployeeProperties ID number is 9 { Welcome from Employee #9 public static void Main() How can I help you? { Employee myEmployee = new Employee(); value becomes 9 myEmployee.IdNumber = 9; Console.WriteLine(“ID number is {0}”, myEmp.IdNumber); myEmployee.WelcomeMessage(); } } Notice how the property is used by an object myEmployee.idNumber = 9; // this would result in an error 24 Using Auto-Implemented Properties Auto-implemented property – The property’s implementation is created for you automatically with the assumption that: The set accessor should simply assign a value to the appropriate field The get accessor should simply return the field When you use an auto-implemented property: – You do not need to declare the field that corresponds to the property 25 Using Auto-Implemented Properties (cont'd.) using System; public static class CreateEmployee3 { public static void Main() { Employee aWorker = new Employee(); aWorker.IdNumber = 3872; aWorker.Salary = 22.11; Console.WriteLine("Employee #{0} makes {1:C}", aWorker.IdNumber, aWorker.Salary); Console.ReadLine(); } } public class Employee { public int IdNumber { get; set; } Notice no private fields public double Salary { get; set; } } 26 More About public and private Access Modifiers Occasionally you need to create public fields or private methods – You can create a public data field when you want all objects of a class to be able to access it A static data field belongs to the entire class, not to any particular instance 27 More About public and private Access Modifiers (cont'd.) public class Carpet { public static string MOTTO = "Our carpets are quality-made"; private int length; private int width; private int area; public int Length { get { return length; } set { length = value; CalcArea(); } } 28 More About public and private Access Modifiers (cont'd.) public int Width { get { return width; } set { width = value; CalcArea(); } } public int Area { get { return area; } } private void CalcArea() { area = Length * Width; } } //Figure 9-13 The Carpet class 29 More About public and private Access Modifiers (cont'd.) The 12 X 14 carpet has an area of 164 Our motto is: Our carpets are quality-made Notice how the static MOTTO is accessed 30 Classes and Instances Recall – Classes are defined to represent a single concept or service. – Each instance of the class contains different data (stored in the instance variables or fields) – The instances all share the same design and have access to the same properties and instance methods The this Reference You might eventually create thousands of objects from a class – Each object does not need to store its own copy of each property and method this reference – Implicitly passed reference When you call a method, you automatically pass the this reference to the method – Tells the method which instance of the class to use 32 Overloading Operators Overload operators – Enable you to use arithmetic symbols with your own objects Overloadable unary operators: + - ! ~ ++ -- true false Overloadable binary operators: + - * / % & | ^ == != > < >=

Use Quizgecko on...
Browser
Browser