Class and Functions Reusable codes.

Slides:



Advertisements
Similar presentations
Object Oriented Programming
Advertisements

Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Encapsulation, toString reading: self-checks: #13-18,
Web Application Development Slides Credit Umair Javed LUMS.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Week 9: Methods 1.  We have written lots of code so far  It has all been inside of the main() method  What about a big program?  The main() method.
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors reading:
Object Oriented Software Development
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Writing Classes (Chapter 4)
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
The Java Programming Language
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
Procedural programming in Java Methods, parameters and return values.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 8 Objects and Classes Object Oriented programming Instructor: Dr. Essam H. Houssein.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Programming Paradigms Lecturer Hamza Azeem. What is PP ? Revision of Programming concepts learned in CPLB Learning how to perform “Object-Oriented Programming”
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Introduction to Object-Oriented Programming Lesson 2.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
Chapter 1 C++ Basics Review (Section 1.4). Classes Defines the organization of a data user-defined type. Members can be  Data  Functions/Methods Information.
Topics Instance variables, set and get methods Encapsulation
OOP Basics Classes & Methods (c) IDMS/SQL News
Structured Programming Dr. Atif Alhejali Lecture 4 Modifiers Parameters passing 1Structured Programming.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Methods, classes, and Objects Dr. Jim Burns. Question  Which of the following access modifiers is the default modifier?  public  private  protected.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Topic: Classes and Objects
Building Java Programs
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Object Based Programming
Object-Oriented Programming
Building Java Programs
Object-Oriented Programming
Building Java Programs
Object-Oriented Programming
Class.
Java Programming Language
Building Java Programs
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

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

real objects in software They are the templates of the 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 static void 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 Every C# class defines a new type. 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); } 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 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); } Class name Variables within a class Function within a class

Classes: Access control 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); } 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 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); } 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 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 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 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 Value Reference main() data section swap() data section Value i Copy of parameter a 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 public static void Main(string[] args) { MyPoint p = new MyPoint(); ...... } 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. Constructor is called Numeric (int,long…) -> 0 Bool -> false Char -> ’\0’ Reference -> null

MyPoint constructor needs two parameters. 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};