OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Advertisements

Handling Errors during the Program Execution Svetlin Nakov Telerik Corporation
Section 5 – Classes. Object-Oriented Language Features Abstraction –Abstract or identify the objects involved in the problem Encapsulation –Packaging.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Corporation
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes Svetlin Nakov Technical Trainer Software University
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.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
JavaScript Design Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers SoftUni.
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
Multidimensional Arrays, Sets, Dictionaries Processing Matrices, Multidimensional Arrays, Dictionaries, Sets SoftUni Team Technical Trainers Software University.
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Functions Reusable Parts of Code SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Technical Trainer Software University
Code Formatting Correctly Formatting the Source Code Svetlin Nakov Technical Trainer Software University
JavaScript Modules and Patterns Private Fields, Module, Revealing Module, Revealing Prototype, … Software University Technical Trainers.
Other Types in OOP Enumerations, Structures, Generic Classes, Attributes SoftUni Team Technical Trainers Software University
Introduction to Object-Oriented Programming Lesson 2.
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University
Console Input / Output Reading and Writing to the Console SoftUni Team Technical Trainers Software University
Processing JSON in.NET JSON, JSON.NET LINQ-to-JSON and JSON to XML SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
C# Advanced Topics Methods, Arrays, Lists, Dictionaries, Strings, Classes and Objects SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Simulating OOP in JavaScript Function Constructor, Prototypes, "this" Object, Classical and Prototypal Model Software University Technical.
Classes, Fields, Constructors, Methods, Properties Svetlin Nakov Telerik Academy academy.telerik.com.
Object-Oriented Programming in Java How Java Implements OOP: Classes, Objects, Exceptions, Etc. SoftUni Team Technical Trainers Software University
Operators and Expressions
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Code Formatting Formatting the Source Code Correctly SoftUni Team Technical Trainers Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
Objects and Classes Using Objects and Classes Defining Simple Classes SoftUni Team Technical Trainers Software University
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
Loops, Methods, Classes Using Loops, Defining and Using Methods, Using API Classes, Exceptions, Defining Classes Svetlin Nakov Technical Trainer
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Static Members Static Variables & Methods SoftUni Team Technical Trainers Software University
Classes, Fields, Constructors, Methods, Properties.
Classes, Fields, Constructors, Methods, Properties Telerik Software Academy Object-Oriented Programming.
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Abstract Classes, Abstract Methods, Override Methods
Creating and Using Objects, Exceptions, Strings
Object-Oriented Programming with C#
Classes, Properties, Constructors, Objects, Namespaces
Repeating Code Multiple Times
Java OOP Overview Classes and Objects, Members and Class Definition, Access Modifier, Encapsulation Java OOP Overview SoftUni Team Technical Trainers.
Iterators and Comparators
What is Encapsulation, Benefits, Implementation in Java
Presentation transcript:

OOP Basic Topics Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University

Table of Contents 1.Defining Simple Classes  Fields, Constructors, Methods, Properties  Access Modifiers  Keeping the Object State 2.Exceptions 3.Generic Classes 4.Attributes 5.Interfaces 2

Defining Simple Classes

 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 Classes in OOP 4

5  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 (per instance) Classes in C#

6 Simple Class Definition public class Cat : Animal { private string name; private string name; 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; } } Field Constructor Property Beginning of class definition Inherited (base) class

7 Simple Class Definition (2) public string Owner public string Owner { get; get; set; set; } public void SayMiau() public void SayMiau() { Console.WriteLine("Miauuuuuuu!"); Console.WriteLine("Miauuuuuuu!"); }} Method End of class definition Automatic Property

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

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 / … 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

10 Constant Fields  Constant fields are of two types:  Compile-time constants – const  Replaced by their value during the compilation  Runtime constants – readonly  Assigned once only at object creation class Math { public const float PI = ; public const float PI = ; public readonly Color = Color.FromRGBA(25, 33, 74, 128); public readonly Color = Color.FromRGBA(25, 33, 74, 128);}

11 Constant Fields – Example 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); // Compilation error: non-static field Console.WriteLine(Constants.Size); // Compilation error: non-static field }}

12 Access Modifiers  Class members can have access modifiers  Used to restrict the access from the other classes  Supports the OOP principle "encapsulation"  Class members can be:  public – accessible from any class  protected – accessible from the class itself and all its descendants  private – accessible from the class itself only  internal (default) – accessible from the current assembly, i.e. the current Visual Studio project

13  The keyword this points to the current instance of the class  Example: The " this " Keyword 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); }}

Using Classes and Objects

15 Dog Meeting – Example 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)

16 Dog Meeting – Example (2) // 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[] { firstDog, secondDog, thirdDog }; Dog[] dogs = new Dog[] { 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(); }}

Dog Meeting Live Demo

Constructors Defining and Using Class Constructors

19  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 have the same name as the class  Have no return type  Can have parameters  Can be private, protected, internal, public What is Constructor?

20  Class Point with parameterless constructor: Defining Constructors 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 …}

21 Defining Constructors (2) 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 a rule constructors should initialize all class fields

22  Pay attention when using inline initialization! Constructors and 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 …}

23  Reusing the constructors (chaining) Chaining Constructors Calls 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 …}

Constructors Live Demo

Methods Defining and Invoking Methods

26  Methods execute some action (some code / some algorithm)  Could be static / per instance  Could be public / private / protected / … Methods 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)); }}

27  Invoking instance methods is done through the object (through the class instance): Using Methods 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));}}

Methods Live Demo

Properties Defining and Using Properties

30  Properties expose object's data to the world  Control how the data is accessed / 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 Why We Need Properties?

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

32 Defining Properties – Example 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 …}

33  Properties are not always bound to a class field  Can be dynamically calculated: Dynamic Properties public class Rectangle { private double width; private double width; private double height; private double height; public double Area public double Area { get get { return width * height; return width * height; } }}

34  Properties could be defined without an underlying field  They are automatically created by the compiler (auto properties) Automatic Properties 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};

Properties Live Demo

Keeping the Object State Correct

37  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 Keep the Object State Correct

38 Keep the Object State – Example 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 a person without specifying a name Incorrect name cannot be assigned

Keeping the Object State Correct Live Demo

What are Exceptions? The Paradigm of Exceptions in OOP

41  The exceptions in.NET Framework / Java are a classic implementation of the OOP exception model  Deliver powerful mechanism for centralized handling of errors and unusual events  Substitute procedure-oriented approach, in which each function returns error code  Simplify code construction and maintenance  Allow the problematic situations to be processed at multiple levels What are Exceptions?

Handling Exceptions Catching and Processing Errors

43  In C# exceptions can be handled by the try-catch-finally construction  catch blocks can be used multiple times to process different exception types Handling Exceptions try{ // Do some work that can raise an exception // Do some work that can raise an exception} catch (SomeException) { // Handle the caught exception // Handle the caught exception}

44 Handling Exceptions – Example static void Main() { string s = Console.ReadLine(); string s = Console.ReadLine(); try try { int.Parse(s); int.Parse(s); Console.WriteLine( Console.WriteLine( "You entered a valid Int32 number {0}.", s); "You entered a valid Int32 number {0}.", s); } catch (FormatException) catch (FormatException) { Console.WriteLine("Invalid integer number!"); Console.WriteLine("Invalid integer number!"); } catch (OverflowException) catch (OverflowException) { Console.WriteLine( Console.WriteLine( "The number is too big to fit in Int32!"); "The number is too big to fit in Int32!"); }}

45  Exceptions in.NET Framework are organized in a hierarchy Exception Hierarchy in.NET

46 How Do Exceptions Work? Main() Method 1 Method 2 Method N 2. Method call 3. Method call 4. Method call … Main() Method 1 Method 2 Method N 8. Find handler 7. Find handler 6. Find handler … 5. Throw an exception.NET CLR 1. Execute the program 9. Find handler 10. Display error message

Call Stack Example Live Demo

Generic Classes Parameterizing Classes

49  Generics allow defining parameterized classes that process data of unknown (generic) type  The class is instantiated (specialized) with different particular types  Example: List  List / List / List / List  Generics are known as "parameterized types" or "template types"  Similar to the templates in C++  Similar to the generics in Java What are Generics?

50 Generic Class – Example 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

Generic Classes Live Demo

Attributes Applying Attributes to Code ElementsApplying Attributes to Code Elements

53 .NET attributes are:  Declarative tags for attaching descriptive information in the declarations in the code  Saved in the assembly at compile time  Objects derived from  Objects derived from System.Attribute  Can be accessed at runtime (through reflection) and manipulated by many tools  Developers can define custom attributes What are Attributes?What are Attributes?

54 Custom Attributes – ExampleCustom Attributes – Example [AttributeUsage(AttributeTargets.Property)] public class MinAttribute : System.Attribute { public int MinValue { get; private set; } public int MinValue { get; private set; } public MinAttribute(int minValue) public MinAttribute(int minValue) { this.MinValue = minValue; this.MinValue = minValue; }} // Example continues public class Book { public Book(string title, int copies) public Book(string title, int copies) { this.Title = title; this.Title = title; this.Copies = copies; this.Copies = copies; } public string Title { get; set; } public string Title { get; set; } [MinAttribute(0)] [MinAttribute(0)] public int Copies { get; set; } public int Copies { get; set; }}

55 Custom Attributes – Example (2)Custom Attributes – Example (2) var book = new Book("Pod Igoto", 1); var properties = book.GetType().GetProperties(); foreach (var property in properties) { foreach (var attribute in property.GetCustomAttributes(false)) foreach (var attribute in property.GetCustomAttributes(false)) { if (attribute is MinAttribute) if (attribute is MinAttribute) { var minAttribute = (MinAttribute) attribute; var minAttribute = (MinAttribute) attribute; int minValue = minAttribute.MinValue; int minValue = minAttribute.MinValue; int actualValue = (int) property.GetValue(book); int actualValue = (int) property.GetValue(book); if (actualValue < minValue) if (actualValue < minValue) { throw new ArgumentOutOfRangeException("Copies cannot be less than 0"); throw new ArgumentOutOfRangeException("Copies cannot be less than 0"); } } }}

56 Interfaces – Example Classes Interfaces

57  Interfaces in C# describe a prototype of group of methods (operations), properties and events  Can be implemented by a class or structure  Define only the signature of the methods / properties  No concrete implementations are provided  Can be used to define abstract data types  Can be inherited (extended) by other interfaces  Cannot be instantiated Interfaces in C#Interfaces in C#

58  Classes can implement multiple interfaces Interfaces – ExampleInterfaces – Example public interface IFormatter { string Format(string name); string Format(string name);} public class FilePrinter { public void Print(IFormatter formatter) public void Print(IFormatter formatter) { string formatted = formatter.Format("pesho"); string formatted = formatter.Format("pesho"); File.WriteAllText(formatted); File.WriteAllText(formatted); }} public class JsonFormatter : IFormatter { public string Format(string name) public string Format(string name) { return "{\"name\":\" + name + "{0}\"}", return "{\"name\":\" + name + "{0}\"}", }} public class XmlFormatter : IFormatter { public string Format(string name) public string Format(string name) { return " " + name + " "; return " " + name + " "; }}

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 59  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "OOP" course by Telerik Academy under CC-BY-NC-SA licenseOOPCC-BY-NC-SA

? ? ? ? ? ? ? ? ? OOP Basic Topics

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg