Defining ClassesDefining Classes
Classes, Fields, Constructors, Methods, PropertiesClasses, Fields, Constructors, Methods, Properties
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. Defining Simple ClassesDefining Simple Classes
2.2. Access ModifiersAccess Modifiers
3.3. Using Classes and ObjectsUsing Classes and Objects
4.4. ConstructorsConstructors
5.5. PropertiesProperties
6.6. Static MembersStatic Members
7.7. Structures in C#Structures in C#
Defining Simple ClassesDefining Simple Classes
Classes in OOPClasses in OOP
 Classes model real-world objects and defineClasses model real-world objects and define
 Attributes (state, properties, fields)Attributes (state, properties, fields)
 Behavior (methods, operations)Behavior (methods, operations)
 Classes describe structure of objectsClasses describe structure of objects
 Objects describe particular instance of a classObjects describe particular instance of a class
 Properties hold information about theProperties hold information about the
modeled object relevant to the problemmodeled object relevant to the problem
 Operations implement object behaviorOperations implement object behavior
Classes in C#Classes in C#
 Classes in C# could have following members:Classes in C# could have following members:
FieldsFields,, constantsconstants,, methodsmethods,, propertiesproperties,,
indexersindexers,, eventsevents,, operatorsoperators,, constructorsconstructors,,
destructorsdestructors
Inner typesInner types ((inner classesinner classes,, structuresstructures,,
interfacesinterfaces,, delegatesdelegates, ...), ...)
 Members can have access modifiers (scope)Members can have access modifiers (scope)
publicpublic,, privateprivate,, protectedprotected,, internalinternal
 Members can beMembers can be
staticstatic ((commoncommon)) or specific for a given objector specific for a given object
5
Simple Class DefinitionSimple Class Definition
public class Cat : Animalpublic 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 Namepublic string Name
{{
get { return name; }get { return name; }
set { name = value; }set { name = value; }
}}
FieldsFields
ConstructorConstructor
PropertyProperty
Begin of class definitionBegin of class definition
Inherited (base)Inherited (base)
classclass
Simple Class Definition (2)Simple Class Definition (2)
public string Ownerpublic string Owner
{{
get { return owner;}get { return owner;}
set { owner = value; }set { owner = value; }
}}
public void SayMiau()public void SayMiau()
{{
Console.WriteLine("Miauuuuuuu!");Console.WriteLine("Miauuuuuuu!");
}}
}}
MethodMethod
End ofEnd of
classclass
definitiondefinition
Class Definition and MembersClass Definition and Members
 Class definition consists of:Class definition consists of:
 Class declarationClass declaration
 Inherited class or implemented interfacesInherited class or implemented interfaces
 Fields (static or not)Fields (static or not)
 Constructors (static or not)Constructors (static or not)
 Properties (static or not)Properties (static or not)
 Methods (static or not)Methods (static or not)
 Events, inner types, etc.Events, inner types, etc.
Access ModifiersAccess Modifiers
Public, Private, Protected, InternalPublic, Private, Protected, Internal
Access ModifiersAccess Modifiers
 Class members can have access modifiersClass members can have access modifiers
Used to restrict the classes able to access themUsed to restrict the classes able to access them
Supports the OOP principle "Supports the OOP principle "encapsulationencapsulation""
 Class members can be:Class members can be:
publicpublic – accessible from any class– accessible from any class
protectedprotected – accessible from the class itself and– accessible from the class itself and
all its descendent classesall its descendent classes
privateprivate – accessible from the class itself only– accessible from the class itself only
internalinternal – accessible from the current– accessible from the current
assembly (used by default)assembly (used by default)
Defining Simple ClassesDefining Simple Classes
ExampleExample
Task: Define ClassTask: Define Class DogDog
 Our task is to define a simple class thatOur task is to define a simple class that
represents information about a dogrepresents information about a dog
The dog should have name and breedThe dog should have name and breed
If there is no name or breed assignedIf there is no name or breed assigned
to the dog, it should be named "Balkan"to the dog, it should be named "Balkan"
and its breed should be "Street excellent"and its breed should be "Street excellent"
It should be able to view and change the nameIt should be able to view and change the name
and the breed of the dogand the breed of the dog
The dog should be able to barkThe dog should be able to bark
Defining ClassDefining Class DogDog – Example– Example
public class Dogpublic 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)(example continues)
Defining ClassDefining Class DogDog – Example– Example (2)(2)
public string Namepublic string Name
{{
get { return name; }get { return name; }
set { name = value; }set { name = value; }
}}
public string Breedpublic string Breed
{{
get { return breed; }get { return breed; }
set { breed = value; }set { breed = value; }
}}
public void SayBau()public void SayBau()
{{
Console.WriteLine("{0} said: Bauuuuuu!", name);Console.WriteLine("{0} said: Bauuuuuu!", name);
}}
}}
Using Classes and ObjectsUsing Classes and Objects
Using ClassesUsing Classes
 How to use classes?How to use classes?
 Create a new instanceCreate a new instance
 Access the properties of the classAccess the properties of the class
 Invoke methodsInvoke methods
 Handle eventsHandle events
 How to define classes?How to define classes?
 Create new class and define its membersCreate new class and define its members
 Create new class using some other as base classCreate new class using some other as base class
How to Use Classes (Non-static)?How to Use Classes (Non-static)?
1.1. Create an instanceCreate an instance
 Initialize fieldsInitialize fields
1.1. Manipulate instanceManipulate instance
 Read / change propertiesRead / change properties
 Invoke methodsInvoke methods
 Handle eventsHandle events
1.1. Release occupied resourcesRelease occupied resources
 Done automatically in most casesDone automatically in most cases
Task: Dog MeetingTask: Dog Meeting
 Our task is as follows:Our task is as follows:
 Create 3 dogsCreate 3 dogs
 First should be named “Sharo”,First should be named “Sharo”, second – “Rex”second – “Rex”
and the last – left without nameand the last – left without name
 Add all dogs in an arrayAdd all dogs in an array
 Iterate through the array elements and askIterate through the array elements and ask
each dog to barkeach dog to bark
 Note:Note:
 Use theUse the DogDog class from the previous example!class from the previous example!
Dog Meeting – ExampleDog Meeting – Example
static void Main()static void Main()
{{
Console.WriteLine("Enter first dog's name: ");Console.WriteLine("Enter first dog's name: ");
dogName = Console.ReadLine();dogName = Console.ReadLine();
Console.WriteLine("Enter first dog's breed: ");Console.WriteLine("Enter first dog's breed: ");
dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using the Dog constructor to set name and breed// Using the Dog constructor to set name and breed
Dog firstDog = new Dog(dogName, dogBreed);Dog firstDog = new Dog(dogName, dogBreed);
Dog secondDog = new Dog();Dog secondDog = new Dog();
Console.WriteLine("Enter second dog's name: ");Console.WriteLine("Enter second dog's name: ");
dogName = Console.ReadLine();dogName = Console.ReadLine();
Console.WriteLine("Enter second dog's breed: ");Console.WriteLine("Enter second dog's breed: ");
dogBreed = Console.ReadLine();dogBreed = Console.ReadLine();
// Using properties to set name and breed// Using properties to set name and breed
secondDog.Name = dogName;secondDog.Name = dogName;
secondDog.Breed = dogBreed;secondDog.Breed = dogBreed;
}}
Dog MeetingDog Meeting
Live DemoLive Demo
ConstructorsConstructors
Defining and Using Class ConstructorsDefining and Using Class Constructors
What is Constructor?What is Constructor?
 Constructors are special methodsConstructors are special methods
 Invoked when creating a new instance of anInvoked when creating a new instance of an
objectobject
 Used to initialize the fields of the instanceUsed to initialize the fields of the instance
 Constructors has the same name as the classConstructors has the same name as the class
 Have no return typeHave no return type
 Can have parametersCan have parameters
 Can beCan be privateprivate,, protectedprotected,, internalinternal,,
publicpublic
Defining ConstructorsDefining Constructors
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
// Simple default constructor// Simple default constructor
public Point()public Point()
{{
xCoord = 0;xCoord = 0;
yCoord = 0;yCoord = 0;
}}
// More code ...// More code ...
}}
 ClassClass PointPoint with parameterless constructor:with parameterless constructor:
Defining Constructors (2)Defining Constructors (2)
public class Personpublic class Person
{{
private string name;private string name;
private int age;private int age;
// Default constructor// Default 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 ruleAs rule
constructorsconstructors
should initialize allshould initialize all
own class fields.own class fields.
Constructors and InitializationConstructors and Initialization
 Pay attention when using inline initialization!Pay attention when using inline initialization!
public class ClockAlarmpublic class ClockAlarm
{{
private int hours = 9; // Inline initializationprivate int hours = 9; // Inline initialization
private int minutes = 0; // Inline initializationprivate int minutes = 0; // Inline initialization
// Default constructor// Default constructor
public ClockAlarm()public ClockAlarm()
{ }{ }
// Constructor with parameters// Constructor with parameters
public ClockAlarm(int hours, int minutes)public ClockAlarm(int hours, int minutes)
{{
this.hours = hours; // Invoked after the inlinethis.hours = hours; // Invoked after the inline
this.minutes = minutes; // initialization!this.minutes = minutes; // initialization!
}}
// More code ...// More code ...
}}
Chaining Constructors CallsChaining Constructors Calls
 Reusing constructorsReusing constructors
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
public Point() : this(0,0) // Reuse constructorpublic 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 ...
}}
ConstructorsConstructors
Live DemoLive Demo
PropertiesProperties
Defining and Using PropertiesDefining and Using Properties
The Role of PropertiesThe Role of Properties
 Expose object's data to the outside worldExpose object's data to the outside world
 Control how the data is manipulatedControl how the data is manipulated
 Properties can be:Properties can be:
 Read-onlyRead-only
 Write-onlyWrite-only
 Read and writeRead and write
 Give good level of abstractionGive good level of abstraction
 Make writing code easierMake writing code easier
Defining PropertiesDefining Properties
 Properties should have:Properties should have:
 Access modifier (Access modifier (publicpublic,, protectedprotected, etc.), etc.)
 Return typeReturn type
 Unique nameUnique name
 GetGet and / orand / or SetSet partpart
 Can contain code processing data in specificCan contain code processing data in specific
wayway
Defining Properties – ExampleDefining Properties – Example
public class Pointpublic class Point
{{
private int xCoord;private int xCoord;
private int yCoord;private int yCoord;
public int XCoordpublic int XCoord
{{
get { return xCoord; }get { return xCoord; }
set { xCoord = value; }set { xCoord = value; }
}}
public int YCoordpublic int YCoord
{{
get { return yCoord; }get { return yCoord; }
set { yCoord = value; }set { yCoord = value; }
}}
// More code ...// More code ...
}}
Dynamic PropertiesDynamic Properties
 Properties are not obligatory bound to a classProperties are not obligatory bound to a class
field – can be calculated dynamicallyfield – can be calculated dynamically
public class Rectanglepublic class Rectangle
{{
private float width;private float width;
private float height;private float height;
// More code ...// More code ...
public float Areapublic float Area
{{
getget
{{
return width * height;return width * height;
}}
}}
}}
Automatic PropertiesAutomatic Properties
 Properties could be defined without anProperties could be defined without an
underlying field behind themunderlying field behind them
It is automatically created by the compilerIt is automatically created by the compiler
33
class UserProfileclass 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() {UserProfile profile = new UserProfile() {
FirstName = "Steve",FirstName = "Steve",
LastName = "Balmer",LastName = "Balmer",
UserId = 91112 };UserId = 91112 };
PropertiesProperties
Live DemoLive Demo
Static MembersStatic Members
Static vs. Instance MembersStatic vs. Instance Members
Static MembersStatic Members
 Static members are associated with a typeStatic members are associated with a type
rather than with an instancerather than with an instance
 Defined with the modifierDefined with the modifier staticstatic
 Static can be used forStatic can be used for
 FieldsFields
 PropertiesProperties
 MethodsMethods
 EventsEvents
 ConstructorsConstructors
Static vs. Non-StaticStatic vs. Non-Static
 StaticStatic::
 Associated with a type, not with an instanceAssociated with a type, not with an instance
 Non-StaticNon-Static::
 The opposite, associated with an instanceThe opposite, associated with an instance
 StaticStatic::
 Initialized just before the type is used for theInitialized just before the type is used for the
first timefirst time
 Non-StaticNon-Static::
 Initialized when the constructor is calledInitialized when the constructor is called
Static Members – ExampleStatic Members – Example
static class SqrtPrecalculatedstatic 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)(example continues)
Static Members – Example (2)Static Members – Example (2)
// Static method// Static method
public static int GetSqrt(int value)public static int GetSqrt(int value)
{{
return sqrtValues[value];return sqrtValues[value];
}}
}}
class SqrtTestclass SqrtTest
{{
static void Main()static void Main()
{{
Console.WriteLine(SqrtPrecalculated.GetSqrt(254));Console.WriteLine(SqrtPrecalculated.GetSqrt(254));
// Result: 15// Result: 15
}}
}}
Static MembersStatic Members
Live DemoLive Demo
C# StructuresC# Structures
C# StructuresC# Structures
 What is a structure in C#What is a structure in C#
A primitive data typeA primitive data type
 Classes are reference typesClasses are reference types
 Examples:Examples: intint,, doubledouble,, DateTimeDateTime
Represented by the key wordRepresented by the key word structstruct
Structures, like classes, have Properties,Structures, like classes, have Properties,
Methods, Fields, ConstructorsMethods, Fields, Constructors
Always have a parameterless constructorAlways have a parameterless constructor
 This constructor cannot be removedThis constructor cannot be removed
Mostly used to store dataMostly used to store data
C# Structures – ExampleC# Structures – Example
struct Pointstruct Point
{{
public int X { get; set; }public int X { get; set; }
public int Y { get; set; }public int Y { get; set; }
}}
struct Colorstruct 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; }
}}
(example continues)(example continues)
C# Structures – Example (2)C# Structures – Example (2)
struct Squarestruct 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 Square(Point location, int size,public Square(Point location, int size,
Color surfaceColor, Color borderColor) : this()Color surfaceColor, Color borderColor) : 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;
}}
}}
Generic ClassesGeneric Classes
Parameterized Classes and MethodsParameterized Classes and Methods
What are Generics?What are Generics?
 Generics allow defining parameterized classesGenerics allow defining parameterized classes
that process data of unknown (generic) typethat process data of unknown (generic) type
The class can be instantiated with severalThe class can be instantiated with several
different particular typesdifferent particular types
Example:Example: List<T>List<T>  List<int>List<int> //
List<string>List<string> // List<Student>List<Student>
 Generics are also known as "Generics are also known as "parameterizedparameterized
typestypes" or "" or "template typestemplate types""
Similar to the templates in C++Similar to the templates in C++
Similar to the generics in JavaSimilar to the generics in Java
Generics – ExampleGenerics – Example
public class GenericList<public class GenericList<TT>>
{{
public void Add(public void Add(TT element) { … }element) { … }
}}
class GenericListExampleclass GenericListExample
{{
static void Main()static void Main()
{{
// Declare a list of type int// Declare a list of type int
GenericList<int> intList =GenericList<int> intList =
new GenericList<int>();new GenericList<int>();
// Declare a list of type string// Declare a list of type string
GenericList<string> stringList =GenericList<string> stringList =
new GenericList<string>();new GenericList<string>();
}}
}}
TT is an unknownis an unknown
type, parameter oftype, parameter of
the classthe class
TT can be used in anycan be used in any
method in the classmethod in the class
Generic ClassesGeneric Classes
Live DemoLive Demo
SummarySummary
 Classes define specific structure for objectsClasses define specific structure for objects
 Objects are particular instances of a class andObjects are particular instances of a class and
use this structureuse this structure
 Constructors are invoked when creating newConstructors are invoked when creating new
class instancesclass instances
 Properties expose the class data in safe,Properties expose the class data in safe,
controlled waycontrolled way
 Static members are shared between allStatic members are shared between all
instancesinstances
 Instance members are per objectInstance members are per object
 Structures are classes that a primitive typeStructures are classes that a primitive type
Defining Classes and ObjectsDefining Classes and Objects
Questions?
http://academy.telerik.com
ExercisesExercises
1.1. Define a class that holds information about a mobileDefine a class that holds information about a mobile
phone device: model, manufacturer, price, owner,phone device: model, manufacturer, price, owner,
battery characteristics (model, hours idle and hoursbattery characteristics (model, hours idle and hours
talk) and display characteristics (size and colors).talk) and display characteristics (size and colors).
Define 3 separate classes:Define 3 separate classes: GSMGSM,, BatteryBattery andand
DisplayDisplay..
2.2. Define several constructors for the defined classesDefine several constructors for the defined classes
that take different sets of arguments (the fullthat take different sets of arguments (the full
information for the class or part of it). The unknowninformation for the class or part of it). The unknown
data fill withdata fill with nullnull..
3.3. Add a static fieldAdd a static field NokiaN95NokiaN95 in thein the GSMGSM class to holdclass to hold
the information about Nokia N95 device.the information about Nokia N95 device.
Exercises (2)Exercises (2)
4.4. Add a method in the classAdd a method in the class GSMGSM for displaying allfor displaying all
information aboutinformation about itit..
5.5. Use properties to encapsulate data fields inside theUse properties to encapsulate data fields inside the
GSMGSM,, BatteryBattery andand DisplayDisplay classes.classes.
6.6. Write a classWrite a class GSMGSMTestTest to testto test the functionality of thethe functionality of the
GSMGSM class:class:
1.1.Create several instances of the class and store themCreate several instances of the class and store them
in an array.in an array.
2.2.Display the information about the createdDisplay the information about the created GSMGSM
instances.instances.
3.3.Display the information about the static memberDisplay the information about the static member
NokiaN95NokiaN95..
Exercises (3)Exercises (3)
7.7. Create a classCreate a class CallCall to hold a call performed throughto hold a call performed through
a GSM. It should contain date, time and duration.a GSM. It should contain date, time and duration.
8.8. Add a propertyAdd a property CallsHistoryCallsHistory in thein the GSMGSM class toclass to
hold a list of the performed calls. Try to use thehold a list of the performed calls. Try to use the
system classsystem class List<Call>List<Call>..
9.9. Add methods in theAdd methods in the GSMGSM class for adding andclass for adding and
deleting calls to the calls history. Add a method todeleting calls to the calls history. Add a method to
clear the call history.clear the call history.
10.10. Add a method that calculates the total price of theAdd a method that calculates the total price of the
calls in the call history. Assume the price per minutecalls in the call history. Assume the price per minute
is given as parameter.is given as parameter.
Exercises (4)Exercises (4)
11.11. Write a classWrite a class GSMCallHistoryTestGSMCallHistoryTest to testto test the callthe call
history functionality of thehistory functionality of the GSMGSM class.class.
 Create an instance of theCreate an instance of the GSMGSM class.class.
 Add few calls.Add few calls.
 Display the information about the calls.Display the information about the calls.
 Assuming that the price per minute is 0.37 calculateAssuming that the price per minute is 0.37 calculate
and print the total price of the calls.and print the total price of the calls.
 Remove the longest call from the historyRemove the longest call from the history
and calculate the total price again.and calculate the total price again.
 Finally clear the call history and print it.Finally clear the call history and print it.
Exercises (5)Exercises (5)
55
12.12. Write generic classWrite generic class GenericList<T>GenericList<T> that keeps athat keeps a
list of elements of some parametric typelist of elements of some parametric type TT. Keep the. Keep the
elements of the list in an array with fixed capacityelements of the list in an array with fixed capacity
which is given as parameter in the class constructor.which is given as parameter in the class constructor.
Implement methodsImplement methods for adding element, accessingfor adding element, accessing
element by index, removing element by index,element by index, removing element by index,
inserting element at given position, clearing the list,inserting element at given position, clearing the list,
finding element by its value andfinding element by its value and ToString()ToString()..
Check all input parameters to avoid accessingCheck all input parameters to avoid accessing
elements at invalid positions.elements at invalid positions.
13.13. Implement auto-grow functionality: when theImplement auto-grow functionality: when the
internal array is full, create a new array of doubleinternal array is full, create a new array of double
size and move all elements to it.size and move all elements to it.
Exercises (6)Exercises (6)
14.14. Define classDefine class FractionFraction that holds information aboutthat holds information about
fractions: numerator and denominator. The formatfractions: numerator and denominator. The format
is "numerator/denominator".is "numerator/denominator".
15.15. Define static methodDefine static method Parse()Parse() which is trying towhich is trying to
parse the input string to fraction and passes theparse the input string to fraction and passes the
values to a constructor.values to a constructor.
16.16. Define appropriate constructors and properties.Define appropriate constructors and properties.
Define propertyDefine property DecimalValueDecimalValue which convertswhich converts
fraction to rounded decimal value.fraction to rounded decimal value.
17.17. Write a classWrite a class FractionTestFractionTest to testto test the functionalitythe functionality
of theof the FractionFraction class. Parse a sequence of fractionsclass. Parse a sequence of fractions
and print their decimal values to the console.and print their decimal values to the console.
Exercises (7)Exercises (7)
18.18. We are given a library of books. Define classes forWe are given a library of books. Define classes for
the library and the books. The library should havethe library and the books. The library should have
name and a list of books. The books have title,name and a list of books. The books have title,
author, publisher, year of publishing and ISBN.author, publisher, year of publishing and ISBN.
Keep the books in List<Book> (first find how to useKeep the books in List<Book> (first find how to use
the classthe class
System.Collections.Generic.List<T>System.Collections.Generic.List<T>).).
19.19. Implement methods for adding, searching by titleImplement methods for adding, searching by title
and author, displaying and deleting books.and author, displaying and deleting books.
20.20. Write a test class that creates a library, adds fewWrite a test class that creates a library, adds few
books to it and displays them. Find all books bybooks to it and displays them. Find all books by
Nakov, delete them and print again the library.Nakov, delete them and print again the library.

14 Defining classes

  • 1.
    Defining ClassesDefining Classes Classes,Fields, Constructors, Methods, PropertiesClasses, Fields, Constructors, Methods, Properties Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2.
    Table of ContentsTableof Contents 1.1. Defining Simple ClassesDefining Simple Classes 2.2. Access ModifiersAccess Modifiers 3.3. Using Classes and ObjectsUsing Classes and Objects 4.4. ConstructorsConstructors 5.5. PropertiesProperties 6.6. Static MembersStatic Members 7.7. Structures in C#Structures in C#
  • 3.
  • 4.
    Classes in OOPClassesin OOP  Classes model real-world objects and defineClasses model real-world objects and define  Attributes (state, properties, fields)Attributes (state, properties, fields)  Behavior (methods, operations)Behavior (methods, operations)  Classes describe structure of objectsClasses describe structure of objects  Objects describe particular instance of a classObjects describe particular instance of a class  Properties hold information about theProperties hold information about the modeled object relevant to the problemmodeled object relevant to the problem  Operations implement object behaviorOperations implement object behavior
  • 5.
    Classes in C#Classesin C#  Classes in C# could have following members:Classes in C# could have following members: FieldsFields,, constantsconstants,, methodsmethods,, propertiesproperties,, indexersindexers,, eventsevents,, operatorsoperators,, constructorsconstructors,, destructorsdestructors Inner typesInner types ((inner classesinner classes,, structuresstructures,, interfacesinterfaces,, delegatesdelegates, ...), ...)  Members can have access modifiers (scope)Members can have access modifiers (scope) publicpublic,, privateprivate,, protectedprotected,, internalinternal  Members can beMembers can be staticstatic ((commoncommon)) or specific for a given objector specific for a given object 5
  • 6.
    Simple Class DefinitionSimpleClass Definition public class Cat : Animalpublic 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 Namepublic string Name {{ get { return name; }get { return name; } set { name = value; }set { name = value; } }} FieldsFields ConstructorConstructor PropertyProperty Begin of class definitionBegin of class definition Inherited (base)Inherited (base) classclass
  • 7.
    Simple Class Definition(2)Simple Class Definition (2) public string Ownerpublic string Owner {{ get { return owner;}get { return owner;} set { owner = value; }set { owner = value; } }} public void SayMiau()public void SayMiau() {{ Console.WriteLine("Miauuuuuuu!");Console.WriteLine("Miauuuuuuu!"); }} }} MethodMethod End ofEnd of classclass definitiondefinition
  • 8.
    Class Definition andMembersClass Definition and Members  Class definition consists of:Class definition consists of:  Class declarationClass declaration  Inherited class or implemented interfacesInherited class or implemented interfaces  Fields (static or not)Fields (static or not)  Constructors (static or not)Constructors (static or not)  Properties (static or not)Properties (static or not)  Methods (static or not)Methods (static or not)  Events, inner types, etc.Events, inner types, etc.
  • 9.
    Access ModifiersAccess Modifiers Public,Private, Protected, InternalPublic, Private, Protected, Internal
  • 10.
    Access ModifiersAccess Modifiers Class members can have access modifiersClass members can have access modifiers Used to restrict the classes able to access themUsed to restrict the classes able to access them Supports the OOP principle "Supports the OOP principle "encapsulationencapsulation""  Class members can be:Class members can be: publicpublic – accessible from any class– accessible from any class protectedprotected – accessible from the class itself and– accessible from the class itself and all its descendent classesall its descendent classes privateprivate – accessible from the class itself only– accessible from the class itself only internalinternal – accessible from the current– accessible from the current assembly (used by default)assembly (used by default)
  • 11.
    Defining Simple ClassesDefiningSimple Classes ExampleExample
  • 12.
    Task: Define ClassTask:Define Class DogDog  Our task is to define a simple class thatOur task is to define a simple class that represents information about a dogrepresents information about a dog The dog should have name and breedThe dog should have name and breed If there is no name or breed assignedIf there is no name or breed assigned to the dog, it should be named "Balkan"to the dog, it should be named "Balkan" and its breed should be "Street excellent"and its breed should be "Street excellent" It should be able to view and change the nameIt should be able to view and change the name and the breed of the dogand the breed of the dog The dog should be able to barkThe dog should be able to bark
  • 13.
    Defining ClassDefining ClassDogDog – Example– Example public class Dogpublic 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)(example continues)
  • 14.
    Defining ClassDefining ClassDogDog – Example– Example (2)(2) public string Namepublic string Name {{ get { return name; }get { return name; } set { name = value; }set { name = value; } }} public string Breedpublic string Breed {{ get { return breed; }get { return breed; } set { breed = value; }set { breed = value; } }} public void SayBau()public void SayBau() {{ Console.WriteLine("{0} said: Bauuuuuu!", name);Console.WriteLine("{0} said: Bauuuuuu!", name); }} }}
  • 15.
    Using Classes andObjectsUsing Classes and Objects
  • 16.
    Using ClassesUsing Classes How to use classes?How to use classes?  Create a new instanceCreate a new instance  Access the properties of the classAccess the properties of the class  Invoke methodsInvoke methods  Handle eventsHandle events  How to define classes?How to define classes?  Create new class and define its membersCreate new class and define its members  Create new class using some other as base classCreate new class using some other as base class
  • 17.
    How to UseClasses (Non-static)?How to Use Classes (Non-static)? 1.1. Create an instanceCreate an instance  Initialize fieldsInitialize fields 1.1. Manipulate instanceManipulate instance  Read / change propertiesRead / change properties  Invoke methodsInvoke methods  Handle eventsHandle events 1.1. Release occupied resourcesRelease occupied resources  Done automatically in most casesDone automatically in most cases
  • 18.
    Task: Dog MeetingTask:Dog Meeting  Our task is as follows:Our task is as follows:  Create 3 dogsCreate 3 dogs  First should be named “Sharo”,First should be named “Sharo”, second – “Rex”second – “Rex” and the last – left without nameand the last – left without name  Add all dogs in an arrayAdd all dogs in an array  Iterate through the array elements and askIterate through the array elements and ask each dog to barkeach dog to bark  Note:Note:  Use theUse the DogDog class from the previous example!class from the previous example!
  • 19.
    Dog Meeting –ExampleDog Meeting – Example static void Main()static void Main() {{ Console.WriteLine("Enter first dog's name: ");Console.WriteLine("Enter first dog's name: "); dogName = Console.ReadLine();dogName = Console.ReadLine(); Console.WriteLine("Enter first dog's breed: ");Console.WriteLine("Enter first dog's breed: "); dogBreed = Console.ReadLine();dogBreed = Console.ReadLine(); // Using the Dog constructor to set name and breed// Using the Dog constructor to set name and breed Dog firstDog = new Dog(dogName, dogBreed);Dog firstDog = new Dog(dogName, dogBreed); Dog secondDog = new Dog();Dog secondDog = new Dog(); Console.WriteLine("Enter second dog's name: ");Console.WriteLine("Enter second dog's name: "); dogName = Console.ReadLine();dogName = Console.ReadLine(); Console.WriteLine("Enter second dog's breed: ");Console.WriteLine("Enter second dog's breed: "); dogBreed = Console.ReadLine();dogBreed = Console.ReadLine(); // Using properties to set name and breed// Using properties to set name and breed secondDog.Name = dogName;secondDog.Name = dogName; secondDog.Breed = dogBreed;secondDog.Breed = dogBreed; }}
  • 20.
  • 21.
    ConstructorsConstructors Defining and UsingClass ConstructorsDefining and Using Class Constructors
  • 22.
    What is Constructor?Whatis Constructor?  Constructors are special methodsConstructors are special methods  Invoked when creating a new instance of anInvoked when creating a new instance of an objectobject  Used to initialize the fields of the instanceUsed to initialize the fields of the instance  Constructors has the same name as the classConstructors has the same name as the class  Have no return typeHave no return type  Can have parametersCan have parameters  Can beCan be privateprivate,, protectedprotected,, internalinternal,, publicpublic
  • 23.
    Defining ConstructorsDefining Constructors publicclass Pointpublic class Point {{ private int xCoord;private int xCoord; private int yCoord;private int yCoord; // Simple default constructor// Simple default constructor public Point()public Point() {{ xCoord = 0;xCoord = 0; yCoord = 0;yCoord = 0; }} // More code ...// More code ... }}  ClassClass PointPoint with parameterless constructor:with parameterless constructor:
  • 24.
    Defining Constructors (2)DefiningConstructors (2) public class Personpublic class Person {{ private string name;private string name; private int age;private int age; // Default constructor// Default 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 ruleAs rule constructorsconstructors should initialize allshould initialize all own class fields.own class fields.
  • 25.
    Constructors and InitializationConstructorsand Initialization  Pay attention when using inline initialization!Pay attention when using inline initialization! public class ClockAlarmpublic class ClockAlarm {{ private int hours = 9; // Inline initializationprivate int hours = 9; // Inline initialization private int minutes = 0; // Inline initializationprivate int minutes = 0; // Inline initialization // Default constructor// Default constructor public ClockAlarm()public ClockAlarm() { }{ } // Constructor with parameters// Constructor with parameters public ClockAlarm(int hours, int minutes)public ClockAlarm(int hours, int minutes) {{ this.hours = hours; // Invoked after the inlinethis.hours = hours; // Invoked after the inline this.minutes = minutes; // initialization!this.minutes = minutes; // initialization! }} // More code ...// More code ... }}
  • 26.
    Chaining Constructors CallsChainingConstructors Calls  Reusing constructorsReusing constructors public class Pointpublic class Point {{ private int xCoord;private int xCoord; private int yCoord;private int yCoord; public Point() : this(0,0) // Reuse constructorpublic 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.
  • 28.
    PropertiesProperties Defining and UsingPropertiesDefining and Using Properties
  • 29.
    The Role ofPropertiesThe Role of Properties  Expose object's data to the outside worldExpose object's data to the outside world  Control how the data is manipulatedControl how the data is manipulated  Properties can be:Properties can be:  Read-onlyRead-only  Write-onlyWrite-only  Read and writeRead and write  Give good level of abstractionGive good level of abstraction  Make writing code easierMake writing code easier
  • 30.
    Defining PropertiesDefining Properties Properties should have:Properties should have:  Access modifier (Access modifier (publicpublic,, protectedprotected, etc.), etc.)  Return typeReturn type  Unique nameUnique name  GetGet and / orand / or SetSet partpart  Can contain code processing data in specificCan contain code processing data in specific wayway
  • 31.
    Defining Properties –ExampleDefining Properties – Example public class Pointpublic class Point {{ private int xCoord;private int xCoord; private int yCoord;private int yCoord; public int XCoordpublic int XCoord {{ get { return xCoord; }get { return xCoord; } set { xCoord = value; }set { xCoord = value; } }} public int YCoordpublic int YCoord {{ get { return yCoord; }get { return yCoord; } set { yCoord = value; }set { yCoord = value; } }} // More code ...// More code ... }}
  • 32.
    Dynamic PropertiesDynamic Properties Properties are not obligatory bound to a classProperties are not obligatory bound to a class field – can be calculated dynamicallyfield – can be calculated dynamically public class Rectanglepublic class Rectangle {{ private float width;private float width; private float height;private float height; // More code ...// More code ... public float Areapublic float Area {{ getget {{ return width * height;return width * height; }} }} }}
  • 33.
    Automatic PropertiesAutomatic Properties Properties could be defined without anProperties could be defined without an underlying field behind themunderlying field behind them It is automatically created by the compilerIt is automatically created by the compiler 33 class UserProfileclass 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() {UserProfile profile = new UserProfile() { FirstName = "Steve",FirstName = "Steve", LastName = "Balmer",LastName = "Balmer", UserId = 91112 };UserId = 91112 };
  • 34.
  • 35.
    Static MembersStatic Members Staticvs. Instance MembersStatic vs. Instance Members
  • 36.
    Static MembersStatic Members Static members are associated with a typeStatic members are associated with a type rather than with an instancerather than with an instance  Defined with the modifierDefined with the modifier staticstatic  Static can be used forStatic can be used for  FieldsFields  PropertiesProperties  MethodsMethods  EventsEvents  ConstructorsConstructors
  • 37.
    Static vs. Non-StaticStaticvs. Non-Static  StaticStatic::  Associated with a type, not with an instanceAssociated with a type, not with an instance  Non-StaticNon-Static::  The opposite, associated with an instanceThe opposite, associated with an instance  StaticStatic::  Initialized just before the type is used for theInitialized just before the type is used for the first timefirst time  Non-StaticNon-Static::  Initialized when the constructor is calledInitialized when the constructor is called
  • 38.
    Static Members –ExampleStatic Members – Example static class SqrtPrecalculatedstatic 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)(example continues)
  • 39.
    Static Members –Example (2)Static Members – Example (2) // Static method// Static method public static int GetSqrt(int value)public static int GetSqrt(int value) {{ return sqrtValues[value];return sqrtValues[value]; }} }} class SqrtTestclass SqrtTest {{ static void Main()static void Main() {{ Console.WriteLine(SqrtPrecalculated.GetSqrt(254));Console.WriteLine(SqrtPrecalculated.GetSqrt(254)); // Result: 15// Result: 15 }} }}
  • 40.
  • 41.
  • 42.
    C# StructuresC# Structures What is a structure in C#What is a structure in C# A primitive data typeA primitive data type  Classes are reference typesClasses are reference types  Examples:Examples: intint,, doubledouble,, DateTimeDateTime Represented by the key wordRepresented by the key word structstruct Structures, like classes, have Properties,Structures, like classes, have Properties, Methods, Fields, ConstructorsMethods, Fields, Constructors Always have a parameterless constructorAlways have a parameterless constructor  This constructor cannot be removedThis constructor cannot be removed Mostly used to store dataMostly used to store data
  • 43.
    C# Structures –ExampleC# Structures – Example struct Pointstruct Point {{ public int X { get; set; }public int X { get; set; } public int Y { get; set; }public int Y { get; set; } }} struct Colorstruct 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; } }} (example continues)(example continues)
  • 44.
    C# Structures –Example (2)C# Structures – Example (2) struct Squarestruct 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 Square(Point location, int size,public Square(Point location, int size, Color surfaceColor, Color borderColor) : this()Color surfaceColor, Color borderColor) : 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; }} }}
  • 45.
    Generic ClassesGeneric Classes ParameterizedClasses and MethodsParameterized Classes and Methods
  • 46.
    What are Generics?Whatare Generics?  Generics allow defining parameterized classesGenerics allow defining parameterized classes that process data of unknown (generic) typethat process data of unknown (generic) type The class can be instantiated with severalThe class can be instantiated with several different particular typesdifferent particular types Example:Example: List<T>List<T>  List<int>List<int> // List<string>List<string> // List<Student>List<Student>  Generics are also known as "Generics are also known as "parameterizedparameterized typestypes" or "" or "template typestemplate types"" Similar to the templates in C++Similar to the templates in C++ Similar to the generics in JavaSimilar to the generics in Java
  • 47.
    Generics – ExampleGenerics– Example public class GenericList<public class GenericList<TT>> {{ public void Add(public void Add(TT element) { … }element) { … } }} class GenericListExampleclass GenericListExample {{ static void Main()static void Main() {{ // Declare a list of type int// Declare a list of type int GenericList<int> intList =GenericList<int> intList = new GenericList<int>();new GenericList<int>(); // Declare a list of type string// Declare a list of type string GenericList<string> stringList =GenericList<string> stringList = new GenericList<string>();new GenericList<string>(); }} }} TT is an unknownis an unknown type, parameter oftype, parameter of the classthe class TT can be used in anycan be used in any method in the classmethod in the class
  • 48.
  • 49.
    SummarySummary  Classes definespecific structure for objectsClasses define specific structure for objects  Objects are particular instances of a class andObjects are particular instances of a class and use this structureuse this structure  Constructors are invoked when creating newConstructors are invoked when creating new class instancesclass instances  Properties expose the class data in safe,Properties expose the class data in safe, controlled waycontrolled way  Static members are shared between allStatic members are shared between all instancesinstances  Instance members are per objectInstance members are per object  Structures are classes that a primitive typeStructures are classes that a primitive type
  • 50.
    Defining Classes andObjectsDefining Classes and Objects Questions? http://academy.telerik.com
  • 51.
    ExercisesExercises 1.1. Define aclass that holds information about a mobileDefine a class that holds information about a mobile phone device: model, manufacturer, price, owner,phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hoursbattery characteristics (model, hours idle and hours talk) and display characteristics (size and colors).talk) and display characteristics (size and colors). Define 3 separate classes:Define 3 separate classes: GSMGSM,, BatteryBattery andand DisplayDisplay.. 2.2. Define several constructors for the defined classesDefine several constructors for the defined classes that take different sets of arguments (the fullthat take different sets of arguments (the full information for the class or part of it). The unknowninformation for the class or part of it). The unknown data fill withdata fill with nullnull.. 3.3. Add a static fieldAdd a static field NokiaN95NokiaN95 in thein the GSMGSM class to holdclass to hold the information about Nokia N95 device.the information about Nokia N95 device.
  • 52.
    Exercises (2)Exercises (2) 4.4.Add a method in the classAdd a method in the class GSMGSM for displaying allfor displaying all information aboutinformation about itit.. 5.5. Use properties to encapsulate data fields inside theUse properties to encapsulate data fields inside the GSMGSM,, BatteryBattery andand DisplayDisplay classes.classes. 6.6. Write a classWrite a class GSMGSMTestTest to testto test the functionality of thethe functionality of the GSMGSM class:class: 1.1.Create several instances of the class and store themCreate several instances of the class and store them in an array.in an array. 2.2.Display the information about the createdDisplay the information about the created GSMGSM instances.instances. 3.3.Display the information about the static memberDisplay the information about the static member NokiaN95NokiaN95..
  • 53.
    Exercises (3)Exercises (3) 7.7.Create a classCreate a class CallCall to hold a call performed throughto hold a call performed through a GSM. It should contain date, time and duration.a GSM. It should contain date, time and duration. 8.8. Add a propertyAdd a property CallsHistoryCallsHistory in thein the GSMGSM class toclass to hold a list of the performed calls. Try to use thehold a list of the performed calls. Try to use the system classsystem class List<Call>List<Call>.. 9.9. Add methods in theAdd methods in the GSMGSM class for adding andclass for adding and deleting calls to the calls history. Add a method todeleting calls to the calls history. Add a method to clear the call history.clear the call history. 10.10. Add a method that calculates the total price of theAdd a method that calculates the total price of the calls in the call history. Assume the price per minutecalls in the call history. Assume the price per minute is given as parameter.is given as parameter.
  • 54.
    Exercises (4)Exercises (4) 11.11.Write a classWrite a class GSMCallHistoryTestGSMCallHistoryTest to testto test the callthe call history functionality of thehistory functionality of the GSMGSM class.class.  Create an instance of theCreate an instance of the GSMGSM class.class.  Add few calls.Add few calls.  Display the information about the calls.Display the information about the calls.  Assuming that the price per minute is 0.37 calculateAssuming that the price per minute is 0.37 calculate and print the total price of the calls.and print the total price of the calls.  Remove the longest call from the historyRemove the longest call from the history and calculate the total price again.and calculate the total price again.  Finally clear the call history and print it.Finally clear the call history and print it.
  • 55.
    Exercises (5)Exercises (5) 55 12.12.Write generic classWrite generic class GenericList<T>GenericList<T> that keeps athat keeps a list of elements of some parametric typelist of elements of some parametric type TT. Keep the. Keep the elements of the list in an array with fixed capacityelements of the list in an array with fixed capacity which is given as parameter in the class constructor.which is given as parameter in the class constructor. Implement methodsImplement methods for adding element, accessingfor adding element, accessing element by index, removing element by index,element by index, removing element by index, inserting element at given position, clearing the list,inserting element at given position, clearing the list, finding element by its value andfinding element by its value and ToString()ToString().. Check all input parameters to avoid accessingCheck all input parameters to avoid accessing elements at invalid positions.elements at invalid positions. 13.13. Implement auto-grow functionality: when theImplement auto-grow functionality: when the internal array is full, create a new array of doubleinternal array is full, create a new array of double size and move all elements to it.size and move all elements to it.
  • 56.
    Exercises (6)Exercises (6) 14.14.Define classDefine class FractionFraction that holds information aboutthat holds information about fractions: numerator and denominator. The formatfractions: numerator and denominator. The format is "numerator/denominator".is "numerator/denominator". 15.15. Define static methodDefine static method Parse()Parse() which is trying towhich is trying to parse the input string to fraction and passes theparse the input string to fraction and passes the values to a constructor.values to a constructor. 16.16. Define appropriate constructors and properties.Define appropriate constructors and properties. Define propertyDefine property DecimalValueDecimalValue which convertswhich converts fraction to rounded decimal value.fraction to rounded decimal value. 17.17. Write a classWrite a class FractionTestFractionTest to testto test the functionalitythe functionality of theof the FractionFraction class. Parse a sequence of fractionsclass. Parse a sequence of fractions and print their decimal values to the console.and print their decimal values to the console.
  • 57.
    Exercises (7)Exercises (7) 18.18.We are given a library of books. Define classes forWe are given a library of books. Define classes for the library and the books. The library should havethe library and the books. The library should have name and a list of books. The books have title,name and a list of books. The books have title, author, publisher, year of publishing and ISBN.author, publisher, year of publishing and ISBN. Keep the books in List<Book> (first find how to useKeep the books in List<Book> (first find how to use the classthe class System.Collections.Generic.List<T>System.Collections.Generic.List<T>).). 19.19. Implement methods for adding, searching by titleImplement methods for adding, searching by title and author, displaying and deleting books.and author, displaying and deleting books. 20.20. Write a test class that creates a library, adds fewWrite a test class that creates a library, adds few books to it and displays them. Find all books bybooks to it and displays them. Find all books by Nakov, delete them and print again the library.Nakov, delete them and print again the library.

Editor's Notes

  • #13 Mew = мяукам!