Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.

Slides:



Advertisements
Similar presentations
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Svetlin Nakov Telerik Corporation
Advertisements

Python Objects and Classes
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Inheritance and Polymorphism.
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
Object-Oriented PHP (1)
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Technical Trainer Telerik Corporation
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Review of C++ Programming Part II Sheng-Fang Huang.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University
Writing Classes (Chapter 4)
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Data Structures Using C++ 2E
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Objects and Classes Chapter 6 CSCI CSCI 1302 – Objects and Classes2 Outline Introduction Defining Classes for Objects Constructing Objects Accessing.
C# D1 CSC 298 Elements of C# code (part 2). C# D2 Writing a class (or a struct)  Similarly to Java or C++  Fields: to hold the class data  Methods:
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
10-Nov-15 Java Object Oriented Programming What is it?
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Classes, Constructors, Properties, Events, Static Members, Interfaces, Inheritance, Polymorphism Doncho Minkov Telerik School Academy schoolacademy.telerik.com.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes SoftUni Team Technical Trainers Software University
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Introduction to Object-Oriented Programming Lesson 2.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Classes, Interfaces and Packages
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Topics Instance variables, set and get methods Encapsulation
Chapter 5 Classes Essential C# Mark Michaelis Ch. 51 Excerpted from Essential C# 4.0 by Mark Michaelis (ISBN: ). Copyright 2010 Pearson Education,
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Telerik Software Academy Object-Oriented Programming.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Object Oriented Programming. Constructors  Constructors are like special methods that are called implicitly as soon as an object is instantiated (i.e.
Classes, Fields, Constructors, Methods, Properties.
Classes, Fields, Constructors, Methods, Properties Telerik Software Academy Object-Oriented Programming.
Static Members and Namespaces
C# for C++ Programmers 1.
Creating and Using Objects, Exceptions, Strings
Object-Oriented Programming with C#
Defining Classes – Part II
Introduction to Classes
Presentation transcript:

Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com

1. Defining Simple Classes 2. Access Modifiers 3. Constructors 4. Properties 5. Static Members 6. Structures in C# 7. Generic Classes 2

 Classes model real-world objects and define  Attributes (state, properties, fields)  Behavior (methods, operations)  Classes describe the structure of objects  Objects describe particular instance of a class  Properties hold information about the modeled object relevant to the problem  Operations implement object behavior 4

 Classes in C# can have members:  Fields, constants, methods, properties, indexers, events, operators, constructors, destructors, …  Inner types (inner classes, structures, interfaces, delegates,...)  Members can have access modifiers (scope)  public, private, protected, internal  Members can be  static (common) or specific for a given object 5

public class Cat : Animal { private string name; private string name; private string owner; private string owner; public Cat(string name, string owner) public Cat(string name, string owner) { this.name = name; this.name = name; this.owner = owner; this.owner = owner; } public string Name public string Name { get { return this.name; } get { return this.name; } set { this.name = value; } set { this.name = value; } } Fields Constructor Property Begin of class definition Inherited (base) class 6

public string Owner public string Owner { get { return this.owner; } get { return this.owner; } set { this.owner = value; } set { this.owner = value; } } public void SayMiau() public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); Console.WriteLine("Miauuuuuuu!"); }} Method End of class definition 7

 Class definition consists of:  Class declaration  Inherited class or implemented interfaces  Fields (static or not)  Constructors (static or not)  Properties (static or not)  Methods (static or not)  Events, inner types, etc. 8

Public, Private, Protected, Internal

 Class members can have access modifiers  Used to restrict the classes able to access them  Supports the OOP principle "encapsulation"  Class members can be:  public – accessible from any class  protected – accessible from the class itself and all its descendent classes  private – accessible from the class itself only  internal (default) – accessible from the current assembly, i.e. current VS project 10

 The keyword this inside a method points to the current instance of the class  Example: 11 class Dog { private string name; private string name; public void PrintName() public void PrintName() { Console.WriteLine(this.name); Console.WriteLine(this.name); // The same like Console.WriteLine(name); // The same like Console.WriteLine(name); }}

Example

 Our task is to define a simple class that represents information about a dog  The dog should have name and breed  If there is no name or breed assigned to the dog  It should be named "Balkan"  Its breed should be "Street excellent"  It should be able to view and change the name and the breed of the dog  The dog should be able to bark 13

public class Dog { private string name; private string name; private string breed; private string breed; public Dog() public Dog() { this.name = "Balkan"; this.name = "Balkan"; this.breed = "Street excellent"; this.breed = "Street excellent"; } public Dog(string name, string breed) public Dog(string name, string breed) { this.name = name; this.name = name; this.breed = breed; this.breed = breed; } (example continues) 14

public string Name public string Name { get { return this.name; } get { return this.name; } set { this.name = value; } set { this.name = value; } } public string Breed public string Breed { get { return this.breed; } get { return this.breed; } set { this.breed = value; } set { this.breed = value; } } public void SayBau() public void SayBau() { Console.WriteLine("{0} said: Bauuu!", this.name); Console.WriteLine("{0} said: Bauuu!", this.name); }} 15

1. Create an instance  Initialize its fields 2. Manipulate the instance  Read / modify properties  Invoke methods  Handle events 3. Release the occupied resources  Done automatically in most cases 17

 Our task is as follows:  Create 3 dogs  The first should be named “Sharo”, the second – “Rex” and the last – left without name  Put all dogs in an array  Iterate through the array elements and ask each dog to bark  Note:  Use the Dog class from the previous example! 18

static void Main() { Console.WriteLine("Enter first dog's name: "); Console.WriteLine("Enter first dog's name: "); string dogName = Console.ReadLine(); string dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: "); Console.WriteLine("Enter first dog's breed: "); string dogBreed = Console.ReadLine(); string dogBreed = Console.ReadLine(); // Use the Dog constructor to set name and breed // Use the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed); Dog firstDog = new Dog(dogName, dogBreed); // Use Dog's parameterless constructor // Use Dog's parameterless constructor Dog secondDog = new Dog(); Dog secondDog = new Dog(); // Use properties to set name and breed // Use properties to set name and breed Console.WriteLine("Enter second dog's name: "); Console.WriteLine("Enter second dog's name: "); secondDog.Name = Console.ReadLine(); secondDog.Name = Console.ReadLine(); Console.WriteLine("Enter second dog's breed: "); Console.WriteLine("Enter second dog's breed: "); secondDog.Breed = Console.ReadLine(); secondDog.Breed = Console.ReadLine(); (example continues) 19

// Create a Dog with default name and breed // Create a Dog with default name and breed Dog thirdDog = new Dog(); Dog thirdDog = new Dog(); // Save the dogs in an array // Save the dogs in an array Dog[] dogs = new Dog[] { Dog[] dogs = new Dog[] { firstDog, secondDog, thirdDog }; firstDog, secondDog, thirdDog }; // Ask each of the dogs to bark // Ask each of the dogs to bark foreach(Dog dog in dogs) foreach(Dog dog in dogs) { dog.SayBau(); dog.SayBau(); }} 20

Live Demo

Defining and Using Class Constructors

 Constructors are special methods  Invoked when creating a new instance of an object  Used to initialize the fields of the instance  Constructors has the same name as the class  Have no return type  Can have parameters  Can be private, protected, internal, public 23

public class Point { private int xCoord; private int xCoord; private int yCoord; private int yCoord; // Simple parameterless constructor // Simple parameterless constructor public Point() public Point() { xCoord = 0; xCoord = 0; yCoord = 0; yCoord = 0; } // More code... // More code...}  Class Point with parameterless constructor: 24

public class Person { private string name; private string name; private int age; private int age; // Parameterless constructor // Parameterless constructor public Person() public Person() { name = null; name = null; age = 0; age = 0; } // Constructor with parameters // Constructor with parameters public Person(string name, int age) public Person(string name, int age) { this.name = name; this.name = name; this.age = age; this.age = age; } // More code... // More code...} As rule constructors should initialize all own class fields. 25

 Pay attention when using inline initialization! public class AlarmClock { private int hours = 9; // Inline initialization private int hours = 9; // Inline initialization private int minutes = 0; // Inline initialization private int minutes = 0; // Inline initialization // Parameterless constructor // Parameterless constructor public AlarmClock() public AlarmClock() { } { } // Constructor with parameters // Constructor with parameters public AlarmClock(int hours, int minutes) public AlarmClock(int hours, int minutes) { this.hours = hours; // Invoked after the inline this.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization! this.minutes = minutes; // initialization! } // More code... // More code...} 26

 Reusing constructors (chaining) public class Point { private int xCoord; private int xCoord; private int yCoord; private int yCoord; public Point() : this(0,0) // Reuse constructor public Point() : this(0,0) // Reuse constructor { } public Point(int xCoord, int yCoord) public Point(int xCoord, int yCoord) { this.xCoord = xCoord; this.xCoord = xCoord; this.yCoord = yCoord; this.yCoord = yCoord; } // More code... // More code...} 27

Live Demo

Defining and Using Properties

 Expose object's data to the outside world  Control how the data is manipulated  Ensure the internal object state is correct  E.g. price should always be kept positive  Properties can be:  Read-only  Write-only  Read and write  Make writing code easier 30

 Properties work as a pair of methods  Getter and setter  Properties should have:  Access modifier ( public, protected, etc.)  Return type  Unique name  Get and / or Set part  Can contain code processing data in specific way, e.g. apply validation 31

public class Point { private int xCoord; private int xCoord; private int yCoord; private int yCoord; public int XCoord public int XCoord { get { return this.xCoord; } get { return this.xCoord; } set { this.xCoord = value; } set { this.xCoord = value; } } public int YCoord public int YCoord { get { return this.yCoord; } get { return this.yCoord; } set { this.yCoord = value; } set { this.yCoord = value; } } // More code... // More code...} 32

 Properties are not obligatory bound to a class field – can be calculated dynamically public class Rectangle { private double width; private double width; private double height; private double height; // More code... // More code... public double Area public double Area { get get { return width * height; return width * height; } }} 33

 Properties could be defined without an underlying field behind them  It is automatically created by the compiler 34 class UserProfile { public int UserId { get; set; } public int UserId { get; set; } public string FirstName { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string LastName { get; set; }}… UserProfile profile = new UserProfile() { FirstName = "Steve", FirstName = "Steve", LastName = "Balmer", LastName = "Balmer", UserId = UserId = 91112};

Live Demo

 Constructors and properties can keep the object's state correct  Can force validation when creating / modifying the object's internal state  Constructors define which properties are mandatory and which are optional  Property setters should validate the new value before saving it in the object field  Invalid values should cause an exception 37

38 public class Person { private string name; private string name; public Person(string name) public Person(string name) { this.Name = name; this.Name = name; } public string Name public string Name { get { return this.name; } get { return this.name; } set set { if (String.IsNullOrEmpty(value)) if (String.IsNullOrEmpty(value)) throw new ArgumentException("Invalid name!"); throw new ArgumentException("Invalid name!"); this.name = value; this.name = value; } }} We have only one constructor, so we cannot create person without specifying a name. Incorrect name cannot be assigned

Live Demo

Static vs. Instance Members

 Static members are associated with a type rather than with an instance  Defined with the modifier static  Static can be used for  Fields  Properties  Methods  Events  Constructors 41

 Static:  Associated with a type, not with an instance  Non-Static:  The opposite, associated with an instance  Static:  Initialized just before the type is used for the first time  Non-Static:  Initialized when the constructor is called 42

static class SqrtPrecalculated { public const int MAX_VALUE = 10000; public const int MAX_VALUE = 10000; // Static field // Static field private static int[] sqrtValues; private static int[] sqrtValues; // Static constructor // Static constructor static SqrtPrecalculated() static SqrtPrecalculated() { sqrtValues = new int[MAX_VALUE + 1]; sqrtValues = new int[MAX_VALUE + 1]; for (int i = 0; i < sqrtValues.Length; i++) for (int i = 0; i < sqrtValues.Length; i++) { sqrtValues[i] = (int)Math.Sqrt(i); sqrtValues[i] = (int)Math.Sqrt(i); } } (example continues) 43

// Static method // Static method public static int GetSqrt(int value) public static int GetSqrt(int value) { return sqrtValues[value]; return sqrtValues[value]; }} class SqrtTest { static void Main() static void Main() { Console.WriteLine( Console.WriteLine( SqrtPrecalculated.GetSqrt(254)); SqrtPrecalculated.GetSqrt(254)); // Result: 15 // Result: 15 }} 44

Live Demo

 What is a structure in C#?  A value data type (behaves like a primitive type)  Examples of structures: int, double, DateTime  Classes are reference types  Declared by the keyword struct  Structures, like classes, have properties, methods, fields, constructors, events, …  Always have a parameterless constructor  This constructor cannot be removed  Mostly used to store data 47

struct Point { public int X { get; set; } public int X { get; set; } public int Y { get; set; } public int Y { get; set; }} struct Color { public byte RedValue { get; set; } public byte RedValue { get; set; } public byte GreenValue { get; set; } public byte GreenValue { get; set; } public byte BlueValue { get; set; } public byte BlueValue { get; set; }} enum Edges { Straight, Rounded } (example continues) (example continues) 48

struct Square { public Point Location { get; set; } public Point Location { get; set; } public int Size { get; set; } public int Size { get; set; } public Color SurfaceColor { get; set; } public Color SurfaceColor { get; set; } public Color BorderColor { get; set; } public Color BorderColor { get; set; } public Edges Edges { get; set; } public Edges Edges { get; set; } public Square(Point location, int size, public Square(Point location, int size, Color surfaceColor, Color borderColor, Color surfaceColor, Color borderColor, Edges edges) : this() Edges edges) : this() { this.Location = location; this.Location = location; this.Size = size; this.Size = size; this.SurfaceColor = surfaceColor; this.SurfaceColor = surfaceColor; this.BorderColor = borderColor; this.BorderColor = borderColor; this.Edges = edges; this.Edges = edges; }} 49

Live Demo

Parameterizing Classes

 Generics allow defining parameterized classes that process data of unknown (generic) type  The class can be instantiated with several different particular types  Example: List  List / List / List  Example: List  List / List / List  Generics are also known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java 52

public class GenericList public class GenericList { public void Add(T element) { … } public void Add(T element) { … }} class GenericListExample { static void Main() static void Main() { // Declare a list of type int // Declare a list of type int GenericList intList = GenericList intList = new GenericList (); new GenericList (); // Declare a list of type string // Declare a list of type string GenericList stringList = GenericList stringList = new GenericList (); new GenericList (); }} T is an unknown type, parameter of the class T can be used in any method in the class T can be replaced with int during the instantiation 53

Live Demo

 Classes define specific structure for objects  Objects are particular instances of a class  Constructors are invoked when creating new class instances  Properties expose the class data in safe, controlled way  Static members are shared between all instances  Instance members are per object  Structures are "value-type" classes  Generics are parameterized classes 55

Questions?

1. Define a class that holds information about a mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and number of colors). Define 3 separate classes (class GSM holding instances of the classes Battery and Display ). 2. Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). Assume that model and manufacturer are mandatory. All unknown data fill with null. 3. Add an enumeration BatteryType (Li-Ion, NiMH, NiCd, …) and use it as a new field for the batteries. 57

4. Add a method in the GSM class for displaying all information about it. Try to override ToString(). 5. Use properties to encapsulate data fields inside the GSM, Battery and Display classes. Ensure all fields hold correct data at any given time. 6. Add a static field and a property IPhone4S in the GSM class to hold the information about iPhone 4 S. 7. Write a class GSMTest to test the GSM class:  Create an array of few instances of the GSM class.  Display the information about the GSMs in the array.  Display the information about the static property IPhone4S. 58

8. Create a class Call to hold a call performed through a GSM. It should contain date, time, dialed phone number and duration (in seconds). 9. Add a property CallHistory in the GSM class to hold a list of the performed calls. Try to use the system class List. 10. Add methods in the GSM class for adding and deleting calls from the calls history. Add a method to clear the call history. 11. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is fixed and is given as parameter. 59

12. Write a class GSMCallHistoryTest to test the call history functionality of the GSM class.  Create an instance of the GSM class.  Add few calls.  Display the information about the calls.  Assuming that the price per minute is 0.37 calculate and print the total price of the calls in the history.  Remove the longest call from the history and calculate the total price again.  Finally clear the call history and print it. 60

Write a generic class GenericList that keeps a list of elements of some parametric type T. Keep the elements of the list in an array with fixed capacity which is given as parameter in the class constructor. Implement methods for adding element, accessing element by index, removing element by index, inserting element at given position, clearing the list, finding element by its value and ToString(). Check all input parameters to avoid accessing elements at invalid positions. 14. Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.

15. Define a class Fraction that holds information about fractions: numerator and denominator. The format is "numerator/denominator", e.g. 1/4. Implement the + and – operators between fractions. 16. Define a static method Parse() which is trying to parse the input string (e.g. -3/4 ) to a fraction and passes the values to a constructor. 17. Define appropriate constructors and properties. Define a property DecimalValue which converts fraction to a rounded decimal value (e.g ). 18. Write a class FractionTest to test the functionality of the Fraction class. Parse a sequence of fractions and print their sum as fraction and as decimal value. 62

19. We are given a library of books. Define classes for the library and the books. The library should have name and a list of books. The books have title, author, publisher, year of publishing and ISBN. Keep the books in List (first find how to use the class System.Collections.Generic.List ). 20. Implement methods for adding, searching by title and author, displaying and deleting books. 21. Write a test class that creates a library, adds few books to it and displays them. Find all books by "Nakov", delete them and print again the library. 63