570 likes | 793 Views
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.
E N D
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 They are the model of real objects in software Objects Classes They are the templates of the objects. Object Oriented Design
Objects Components that are required to run a car: Motor, wheels, steering wheel, wiper etc. etc. Real World Computer
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 staticvoid Main(string[] args) { Car c = new Car(1999,"Honda"); if(c.getGear() != 0) { c.changeGear(0); } c.startEngine(); c.pushClutch(0); c.changeGear(1); ..... ..... } • The basic function of a class is defining data and procedures that are used in an object. • Class is a abstract correspondence of an object. • Abstraction is a fundamental element in OOP design. Object Class name/Type
Classes publicclassPoint { // private section // restricts access to itself private doublex; private doubley; // interface: accessible from // any code // procedure that finds distance //from origin public doublegetDistanceOrigin() { returnMath.Pow(x*x+y*y,0.5); } } • 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.
Classes: Access control publicclassPoint { // private section // restricts access to itself private doublex; private doubley; // interface: accessible from // any code // procedure that finds distance //from origin public doublegetDistanceOrigin() { returnMath.Pow(x*x+y*y,0.5); } } Class name Variables within a class Function within a class
Classes: Access control publicclassPoint { // private section // restricts access to itself private doublex; private doubley; // interface: accessible from // any code // procedure that finds distance //from origin public doublegetDistanceOrigin() { returnMath.Pow(x*x+y*y,0.5); } } private: where internal data and functions resides public:defines interfaces (data and functions) that are accessible from outside.
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 publicclassPoint { // private section // restricts access to itself doublex; doubley; // interface: accessible from // any code // procedure that finds distance //from origin public doublegetDistanceOrigin() { returnMath.Pow(x*x+y*y,0.5); } } • Default access level in a class is private. • If there is no explicit access level keyword then, access level is implicitly defined as private.
Structure of a C# program publicclass 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_typeFuntion_name (Parameters)
Functions • Functions should reside within a class. • We can not write a function that is not defined in a class. publicclass 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 addis 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 a copied 12 12 j b copied 25 25 k c copied 45 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 Function can not perform swap operation. a and b are local variables which are defined only in the function.
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 swap() data section Value i a Copy of parameter 12 12 main() data seciton swap() data section Reference &i Actual parameter &i 12 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…) -> 0 Bool -> false Char -> ’\0’ Reference -> 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?