Classes, Fields, Constructors, Methods, Properties Telerik Software Academy Object-Oriented Programming.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Coding JavaScript the expressive way Learning & Development Telerik Software Academy.
Asynchronous Programming with C# and WinRT
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Handling Errors during the Program Execution Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Using the Standard.NET Framework Classes Telerik Software Academy C# Fundamentals – Part 2.
OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Polymorphism, Class Hierarchies, Exceptions, Strong Cohesion and Loose Coupling Telerik Software Academy Object-Oriented Programming.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy.
Using the Standard.NET Framework Classes Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Classes, Fields, Constructors, Methods, Properties.
Object-Oriented Programming with C#
Presentation transcript:

Classes, Fields, Constructors, Methods, Properties Telerik Software Academy Object-Oriented Programming

1. Defining Simple Classes 2. Fields 3. Access Modifiers 4. Using Classes and Objects 5. Constructors 6. Methods 7. Properties 8. Enumerations (Enums) 9. Keeping the Object State 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

Defining and Using Data Fields

 Fields are data members defined inside a class  Fields hold the internal object state  Can be static or per instance  Can be private / public / protected / … 10 class Dog { private string name; private string name; private string breed; private string breed; private int age; private int age; protected Color color; protected Color color;} Field declarations

 Constant fields are of two types:  Compile-time constants – const  Replaced by their value during the compilation  Can contain only values, known at compile time  Runtime constants – readonly  Assigned once only at object creation  Can contain values, calculated run time 11 class Math { public const float PI = ; public const float PI = ; public readonly Color = public readonly Color = Color.FromRGBA(25, 33, 74, 128); Color.FromRGBA(25, 33, 74, 128);} More info More info

12 public class Constants { public const double PI = ; public const double PI = ; public readonly double Size; public readonly double Size; public Constants(int size) public Constants(int size) { this.Size = size; // Cannot be further modified! this.Size = size; // Cannot be further modified! } static void Main() static void Main() { Console.WriteLine(Constants.PI); Console.WriteLine(Constants.PI); Constants c = new Constants(5); Constants c = new Constants(5); Console.WriteLine(c.Size); Console.WriteLine(c.Size); c.Size = 10; // Compilation error: readonly field c.Size = 10; // Compilation error: readonly field Console.WriteLine(Constants.Size); // compile error Console.WriteLine(Constants.Size); // compile error }}

Public, Private, Protected, Internal

 Class members can have access modifiers  Restrict the access to them from outer sources  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. the current VS project 14

15 protected internal protected internal private public

 The keyword this inside a method points to the current instance of the class  Example: 16 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  Optional fields (could be null )  The class allows to view and modify the name and the breed at any time  The dog should be able to bark 18

public class Dog { private string name; private string name; private string breed; private string breed; public Dog() public Dog() { } public Dog(string name, string breed) public Dog(string name, string breed) { this.name = name; this.name = name; this.breed = breed; this.breed = breed; } (the example continues) 19

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: Bauuuuuu!", Console.WriteLine("{0} said: Bauuuuuu!", this.name ?? "[unnamed dog]"); this.name ?? "[unnamed dog]"); }} 20

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

 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! 23

static void Main() { Console.Write("Enter first dog's name: "); Console.Write("Enter first dog's name: "); string dogName = Console.ReadLine(); string dogName = Console.ReadLine(); Console.Write("Enter first dog's breed: "); Console.Write("Enter first dog's breed: "); string dogBreed = Console.ReadLine(); string dogBreed = Console.ReadLine(); // Use the Dog constructor to assign name and breed // Use the Dog constructor to assign 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 assign name and breed // Use properties to assign name and breed Console.Write("Enter second dog's name: "); Console.Write("Enter second dog's name: "); secondDog.Name = Console.ReadLine(); secondDog.Name = Console.ReadLine(); Console.Write("Enter second dog's breed: "); Console.Write("Enter second dog's breed: "); secondDog.Breed = Console.ReadLine(); secondDog.Breed = Console.ReadLine(); (the example continues) 24

// Create a Dog with no name and breed // Create a Dog with no 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(); }} 25

Live Demo

Defining and Using Class Constructors

 Constructors are special methods  Invoked at the time of 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 28

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() { this.xCoord = 0; this.xCoord = 0; this.yCoord = 0; this.yCoord = 0; } // More code … // More code …}  Class Point with parameterless constructor: 29

public class Person { private string name; private string name; private int age; private int age; // Parameterless constructor // Parameterless constructor public Person() public Person() { this.name = null; this.name = null; this.age = 0; this.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. 30

 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 (intentionally left empty) // Parameterless constructor (intentionally left empty) 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 …} 31

 Reusing constructors (chaining) public class Point { private int xCoord; private int xCoord; private int yCoord; private int yCoord; public Point() : this(0, 0) // Reuse the constructor public Point() : this(0, 0) // Reuse the 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 …} 32

Live Demo

Defining and Invoking Methods

 Methods are class members that execute some action (some code, some algorithm)  Could be static / per instance  Could be public / private / protected / … 35 public class Point { private int xCoord; private int xCoord; private int yCoord; private int yCoord; public double CalcDistance(Point p) public double CalcDistance(Point p) { return Math.Sqrt( return Math.Sqrt( (p.xCoord - this.xCoord) * (p.xCoord - this.xCoord) + (p.xCoord - this.xCoord) * (p.xCoord - this.xCoord) + (p.yCoord - this.yCoord) * (p.yCoord - this.yCoord)); (p.yCoord - this.yCoord) * (p.yCoord - this.yCoord)); }}

 Invoking instance methods is done through the object (class instance): 36 class TestMethods { static void Main() static void Main() { Point p1 = new Point(2, 3); Point p1 = new Point(2, 3); Point p2 = new Point(3, 4); Point p2 = new Point(3, 4); System.Console.WriteLine(p1.CalcDistance(p2)); System.Console.WriteLine(p1.CalcDistance(p2));}}

Live Demo

Defining and Using Properties

 Properties expose object's data to the 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 (examples) examples  Read and write  Simplify the writing of code 39

 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 40

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...} 41

 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; } }} 42

 Properties could be defined without an underlying field behind them  It is automatically created by the compiler 43 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

Defining and Using Enumerated Types

 Enumerations are types that hold a value from a fixed set of named constants  Declared by enum keyword in C# 46 public enum DayOfWeek { Mon, Tue, Wed, Thu, Fri, Sat, Sun Mon, Tue, Wed, Thu, Fri, Sat, Sun} class EnumExample { static void Main() static void Main() { DayOfWeek day = DayOfWeek.Wed; DayOfWeek day = DayOfWeek.Wed; Console.WriteLine(day); // Wed Console.WriteLine(day); // Wed }}

47 public enum CoffeeSize { Small = 100, Normal = 150, Double = 300 Small = 100, Normal = 150, Double = 300} public class Coffee { private CoffeeSize size; private CoffeeSize size; public Coffee(CoffeeSize size) public Coffee(CoffeeSize size) { this.size = size; this.size = size; } public CoffeeSize Size public CoffeeSize Size { get { return this.size; } get { return this.size; } }} (the example continues)

48 public class CoffeeMachine { static void Main() static void Main() { Coffee normalCoffee = new Coffee(CoffeeSize.Normal); Coffee normalCoffee = new Coffee(CoffeeSize.Normal); Coffee doubleCoffee = new Coffee(CoffeeSize.Double); Coffee doubleCoffee = new Coffee(CoffeeSize.Double); Console.WriteLine("The {0} coffee is {1} ml.", Console.WriteLine("The {0} coffee is {1} ml.", normalCoffee.Size, (int)normalCoffee.Size); normalCoffee.Size, (int)normalCoffee.Size); // The Normal coffee is 150 ml. // The Normal coffee is 150 ml. Console.WriteLine("The {0} coffee is {1} ml.", Console.WriteLine("The {0} coffee is {1} ml.", doubleCoffee.Size, (int)doubleCoffee.Size); doubleCoffee.Size, (int)doubleCoffee.Size); // The Double coffee is 300 ml. // The Double coffee is 300 ml.}}

Live Demo

 Constructors and properties can keep the object's state correct  This is known as encapsulation in OOP  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 51

52 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

 Classes define specific structure for objects  Objects are particular instances of a class  Classes define fields, methods, constructors, properties and other members  Access modifiers limit the access to class members  Constructors are invoked when creating new class instances and initialize the object's internal state  Enumerations define a fixed set of constants  Properties expose the class data in safe, controlled way 54

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com