Class and Functions Reusable codes Object Oriented Design First concept of object oriented programming is emerged at 60‘s. Smalltalk language which is introduced at 1972 was first object oriented programming language. Smalltalk has defined essentials and rules of object oriented programming. In 80’s C++ came out and made object oriented programming a de-facto standard. C# and Java programming languages which are successors of C++, has widespread usage nowadays. Object Oriented Design Concepts and Design Process OOP – Essential Concepts OOP – Essential Concepts OOP – Essential Concepts OOP Procedural Programming Collection of interacting objects List of subroutines Data is private, accessed by using methods Data is global Generally bugs are local Bugs can span anywhere within a program Reusable objects Reusable functions OOP – Essential Concepts They are the model of real objects in software Objects Classes They are the templates of the objects. Object Oriented Design Objects Real World Computer Components that are required to run a car: Motor, wheels, steering wheel, wiper etc. etc. Classes A class is a construct that has code and data sections which are used for modeling real life objects. Makes programming modular. Both code and data may reside in a class. Modeling is the base of coding. Object – Class ? Class is a definition of an object. It is an abstract concept. Object is an instance of a class. It is a quantity of concrete. Example; Human class is a definition set but, every one of us is an instance of Human class. Classes • The basic function of static void Main(string[] args) Object a class is defining { data and procedures Car c = new Car(1999,"Honda"); that are used in an if(c.getGear() != 0) { object. Class name/Type c.changeGear(0); } • Class is a abstract correspondence of an c.startEngine(); object. c.pushClutch(0); c.changeGear(1); • Abstraction is a ..... fundamental element ..... } in OOP design. Classes Every C# class defines a new type. Object is an instance of a class that is created in memory. Classes has interfaces and code sections. Interfaces are accessible functions and member variables, code sections defines what can this class do. Design of interface is a critical point. Classes hide their data and functionality by using “private” keyword. “public” defines interfaces. public class Point { // private section // restricts access to itself private double x; private double y; // interface: accessible from // any code } // procedure that finds distance //from origin public double getDistanceOrigin() { return Math.Pow(x*x+y*y,0.5); } Classes: Access control Class name Variables within a class public class Point { // private section // restricts access to itself private double x; private double y; // interface: accessible from // any code Function within a class } // procedure that finds distance //from origin public double getDistanceOrigin() { return Math.Pow(x*x+y*y,0.5); } Classes: Access control private: where internal data and functions resides public class Point { // private section // restricts access to itself private double x; private double y; // interface: accessible from // any code public: defines interfaces (data and functions) that are accessible from outside. } // procedure that finds distance //from origin public double getDistanceOrigin() { return Math.Pow(x*x+y*y,0.5); } Classes: Access control In C# language there are three mostly used keywords that are used for defining access levels to member variables and functions. private: it is the section where internal member variables and functions resides, is not accessible from outside of the class. public: it is the section where interfaces are defined. Member variables and functions are accessible from any other code. protected: it is the section which includes member variables and functions that can be accessible from derived classes. It is not accessible from outside of class. Classes: Access control • Default access level in a class is private. • If there is no explicit access level keyword then, access level is implicitly defined as private. public class Point { // private section // restricts access to itself double x; double y; // interface: accessible from // any code } // procedure that finds distance //from origin public double getDistanceOrigin() { return Math.Pow(x*x+y*y,0.5); } Structure of a C# program public class Point { double x,y,z; public void distanceFromOrigin() { return ….; } } Executable program + public static void Main(string[] args) { Point n = new Point(); ...... } Classes: Usage Lets define a Car class. There will be two public member variables named Brand and Model and a public function class Run. Run function will display some motor sound to the display. Classes: Usage If we want to use class Car first we should crate an object with type Car. After definition we can call functions and set values to the member variables in the interface. Object Class name Value assignment Function call Exercise Write a class named Human. Properties Name Surname Age Create an object instance of the class and assign values to it. Print assigned values to the screen. Classes - Functions There are lots of functionality in OOP. Encapsulation Polymorphism Inheritance Before diving into these properties lets look at functions Functions Functions are integrities of variables and expressions that are used to fulfill a job. They take definite parameter types and have definite return types. They can be called again and again from other code sections of a program. Basic definition: return_type Funtion_name (Parameters) Functions Functions should reside within a class. We can not write a function that is not defined in a class. public class MyClass { public void function() { do something; } } Functions We used just one function till now, which is; static void Main(string[] args). Notation: static void Main(string[] args) { /* definitions */ /* expressions */ } void keyword means that this function will not return a value. Functions () brackets implies that Main is a function. Parameters that are meant to be send to function will be written within these brackets. In this example Main(string[] args) function could take string[] type parameters. Generally functions use parameter lists. They perform and return output depending on the values of these parameters. Functions We use a function in two steps. These are; Writing function itself (function definition + statements within this function) Statement that calls the function. Function definition There is no “;” after function definition private float add(int a, int b, int c) Here, function named add requires three parameters named a, b and c. Function returns a value with float type. The values of variables a, b and c are assigned by the statement which calls that function. Function definition Function is composed of function definition, and statements surrounded by curly brackets: private float add( int a, int b, int c) { float t; t = a + b + c ; return t; } Note: Curly brackets determines stating and ending point of a function. Function definition private float add( int a, int b, int c) { float t; t = a + b + c ; return t; } Variables a, b and c are valid only in function add. Variable t which is defined in the function add is valid only in the function and deleted after function execution is finished. Function definition Functions use keyword return to return a result to calling. If return type is void, then we don’t need to use keyword return. return keyword should return a value with a type that should exactly match with the type defined in the function. private float add( int a, int b, int c) { float t; t = a + b + c ; return t; } Function calls Function definition should be taken into account while calling a function. Function parameters could be constants as well as variables. Usually the value returned from function is assigned to a variable. value = add( i, j, k ); or value = add( 5, x, 2.7 ); Function call When add function is called from main() function, the values that resides in main() data section are copied to the data section of add() function. main() data section add() data section i 12 j 25 k 45 copied copied copied a 12 b 25 c 45 Exercise: Factorial Function Write a class that has a function which calculates the factorial of a given number. This function will return 0 from numbers smaller than zero and returns 1 for numbers 0 and 1. Calculate the factorial of numbers by using a loop for numbers greater than 1. Write a main function that prints the factorials of numbers between 1 and 10. Remember that you should use the class and function that we wrote in our program. Exercise: Factorial Function Class name Function name Return type Parameter Exercise: Factorial Function Object Class name Function call Exercise Write a function that takes two parameters and returns the differences of factorials of these two numbers. Function prototype: int factorial_difference(int a, int b) This function may call the factorial() function written before. You may use the same class where factorial() function is defined. Exercise Usage of this function will be; Example Write a function that swaps the values of its two parameters. It seems that first output should be “5 3" and second one should be“3 5". Example a and b are local variables which are defined only in the function. Function can not perform swap operation. Why it didn’t work? Functions accepts two types of parameters. value Reference By Value: Instead of actual parameters, copies of parameter values are used while calling a function. By Reference: Addresses of parameters are send while calling a function. If function modified the variable at this address, then the actual value is modified (e.g. The main variable in main function) Values - References main() data section Value Reference i 12 swap() data section Copy of parameter main() data seciton &i 12 a 12 swap() data section Actual &i parameter 12 References ref keyword is used for sending the actual parameter itself to a funtion as a parameter. In the function definition, you should put ref keyword in front of the parameter which meant to be used as reference parameter. Similarly, ref keyword is used before reference variable while function is called. Example - Fix Change the parameters of the function to reference type by adding ref keyword in front of them. Example - Fix When we call the function with ref keywod, you will see that funcion is working propely . Classes: Constructor Constructor functions are called during creation of object. Constructor function and classes have same names. Constructors does not have a return type (even void) There can be multiple constructors. Each should have different parameters (different signatures). If there isn’t a constructor defined, then default constructor is used. Classes: Constructor There could be just one parameterless default contructor. Constructor is called whan an object is created with new keyword. Primitive types can be created without using contrutor and have default values. public static void Main(string[] args) { MyPoint p = new MyPoint(); ...... } Constructor is called Numeric (int,long…) Bool Char Reference -> -> -> -> 0 false ’\0’ null Classes: Constructor While objects are created from classes, we should use contrutors and their parameters. MyPoint constructor needs two parameters. Exercise Write a MyTime class, with • Two constructors • A function that print time • A function used for adding time Use all methods of MyTime class in Main function Classes: Static Members • Static members that are defined in a class can be accessed without using an object instance of that class. • Static members use only one memory location and one copy. A value change from one code section will affect all following uses of that member. • Static members can be used for transferring data between objects. • Static members defined by using static keyword. Classes: Static Members Assume that we are writing a computer game. In this game we are modeling alien race named Martians. Martians attack if there are at least 3 Martians, else they do not dare to attack. Question is: How each martial will know the number of Martians around? Classes: Static Members In addition of members, classes can also have static functions. Static method Function is called without using an object Classes: Static Members We don’t need objects to call static functions. ToInt32 function is called without creating a Convert object Exercise Write a class ConvertTemperature which makes convertions between different temperature units. ConvertTemperature class will perform conversion betwreen Celcius, Fahrenheit ve Kelvin units. Conversion functions should be static. In other words we shouldn’t need an object to make conversion. Formulas: Tc=(5/9)*(Tf-32) Tc = Tk - 273.18 const and readonly members C# language offers constant variables whose values can not be changed. We use const or readonly keywords to define constant variables in a class. We should assign values to const variables at the definiton phase. We should assign values to readonly variables at the definiton phase or at the constructor of the class. After these phases, we can not change values of these const and readonly variables. const and readonly members Error! Trying to change const variable. Enumerations C# language has the feature of creating custom types. It increases the readability of the program code. As an example, we can create an enumeration that exists in a grub of people: Enum Workers{ Laborer, Officer, Director, Retired};