Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECT ORIENTED PROGRAMMING INTRODUCTION. WHAT IS OBJECT-ORIENTATION ALL ABOUT? Principles and techniques for system modeling which: Aim to produce a.

Similar presentations


Presentation on theme: "OBJECT ORIENTED PROGRAMMING INTRODUCTION. WHAT IS OBJECT-ORIENTATION ALL ABOUT? Principles and techniques for system modeling which: Aim to produce a."— Presentation transcript:

1 OBJECT ORIENTED PROGRAMMING INTRODUCTION

2 WHAT IS OBJECT-ORIENTATION ALL ABOUT? Principles and techniques for system modeling which: Aim to produce a model of a system manage complexity inherent in analysis, design, and implementation provide methodology for system development provide integrated view of hardware and software

3 HOW? “ Using object-orientation as a base, we model a system as a number of objects that interacts.”

4 OBJECT ORIENTED SYSTEM (OOS) Modelling the system by representing a collection of objects in it Each object represents some part of the system that is independent of other parts The different objects can collaborate to perform a task Interaction between objects through messages

5 IS IT ANY GOOD? A system which is designed and modeled using an object-oriented technology is: Easy to understand Directly related to reality - reduces the semantic gap between reality and models Natural partitioning of the problem More flexible and resilient to change - allows local modification to models Systems can be developed more rapidly and at a lower cost

6 OO PROGRAMMING

7 Object-oriented Programming What is OOP? – OOP is a programming paradigm based on three simple core concepts: Classes: – Are “types” of “things” that we can talk about. Objects: – Are “instances” or examples of classes. Message passing: – Objects interact with each other by passing messages to ask each other to carry out their methods (behaviours).

8 OO PROGRAMMING DESIGN Let’s consider two doors D1 and D2. We aim to develop an application monitoring these doors. What actions may be applied on these doors: Open and close. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 8

9 OO PROGRAMMING DESIGN In Object-Oriented programming: The doors are considered as active entities of the real world capable of interacting with their environments. Each one of them offers two services open and close.  Open()  Close() In order to open or to close a door, the user should: Order the appropriate door to perform the required action. d.Open(); or d.Close(); where d is either D1 or D2 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 9

10 Why OO programming? Modularity - large software projects can be split up in smaller pieces. Reusability - Programs can be assembled from pre-written software components. Extensibility - New software components can be written or developed from existing ones.

11 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 11 Objects Objects are key-concept to understand object- oriented technology. Objects are entities of the real-world that may interact with their environments by performing services on demand. Examples of real-world objects: your Car, your Cell- phone, the coffee slot-machine. Each Nokia-N71 cell-phone is an object and may execute some services.

12 WHAT IS AN OBJECT? Tangible Things as a car, printer,... Roles as employee, boss,... Incidents as flight, overflow,... Interactions as contract, sale,... Specifications as colour, shape, … 12

13 WHAT IS AN OBJECT? An object represents an individual, identifiable item, unit, or entity, either real or abstract, with a well-defined role in the problem domain. An object is anything to which a concept applies. An object is a “noun”

14 HOW TO DEFINE AN OBJECT? An object is defined by: Attributes (also called fields) Behaviour---what it can do? (also called methods) Example A man can be defined by: Attributes: name, age, job, address,..etc Behaviour: talk, walk, eat, work, study,...etc How to define a bird? A car? A flight?

15 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 15 Classes Objects of the real world may be classified into types: Cars, Cell-Phones, CD Players, etc. Objects of the same type have the same characteristics and are manufactured using the same blueprint. A class is a blueprint or prototype from which objects of the same type are created. A class describes a set of objects having the same characteristics and offering the same services.

16 CLASS A class represents a template for several objects and describes how these objects are structured internally Objects of the same class have the same definition both for their operations and their information structure Classes are types of things

17 CLASS VS. OBJECT Class People John, George, Sara are objects that can be instantiated from the people class Class Vehicle Bus, car, train are objects (instances of the vehicle class) Class Car The blue Nissan, the red Vauxhall, my uncle’s car are objects (instances of the car class)

18 CLASS VS. OBJECT (CONT.) Find a class to represent the following items: dog, cat, lion, tiger chair, table, wardrobe banana, orange, apple breakfast, lunch, dinner Provide examples of objects that can be instantiated from the following classes Students, Courses, Modules

19 Instance An instance is an object created from a class A class describes the behavior and information structure of an instance, while the current state of the instance is defined by the operations performed on the instance System’s behavior is performed via the interactions between instances

20 SUMMARY – OO BASICS Fundamental concepts – Object, Class, Field/attribute, Method, Parameter Objects –Represent “things” from the real world, or from some problem domain (e.g. “the red car in the car park”) Classes –Objects are created from classes –Represent all objects of a kind (e.g. all “cars”)

21 OBJECT-ORIENTED BASICS Fields/attributes –Classes define fields (e.g. a Person class could contain fields name, age, sex, etc.) –Objects have attributes, which are values stored in fields (e.g. person_1 has attributes “John Smith”, 25, Male) –An object’s state is defined by its attributes Methods –Classes define methods, which can access or change attributes –Objects communicate by calling (invoking) each others’ methods Parameters –Methods can have parameters to pass additional information during execution

22 OBJECT ORIENTED PROGRAMMING BASIC PRINCIPLES

23 UML REPRESENTATION FOR OBJECT ORIENTED SYSTEMS UML (Unified Modeling Language) is a graphical representation scheme used for modeling object oriented systems An OO system is designed using this language in a form of diagrams, with one standard set of graphical notations Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 23

24 What is a Class Diagram? A class diagram is a graphical representation that describes the types of objects in the system and the various kinds of relationships that exist among them. A central modeling technique that runs through nearly all object-oriented methods. The richest notation in UML.

25 UML REPRESENTATION OF A CLASS UML represents a class with a rectangle having 3 compartments stacked vertically. The top compartment shows the class's name. The middle compartment lists the attributes. The bottom compartment lists the operations: methods or services. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 25 Methods (Services) Attributes ClassName - att 1 : dataType 1 -… - att i : dataType i + m 1 (…): dataType 1 +... + m j (…): dataType j

26 Essential Elements of a UML Class Diagram Class name (top) Attributes/ fields (middle) Methods (bottom) Links between different classes define relationships (will be covered in CSC113) Student - name: string - age: int +AttendLect):void +Study():void Class Name Attributes Methods

27 27 UML Representation of a Class (UML Class Diagram) UML uses three symbols to represent the visibility of the class’ members. + : mentions that the member is public. - : mentions that the member is private. # : introduced in the CSC 113. Methods (Services) Attributes ClassName - att 1 : dataType 1 -… - att i : dataType i + m 1 (…): dataType 1 +... + m j (…): dataType j

28 HOW TO CREATE UML from problem definition: 1.Identify all (relevant) nouns and verbs 2.From List of nouns,select objects 3.Identify data component for each object 4.From list of verbs, select operation 28

29 UML REPRESENTATION OF A CLASS (UML CLASS DIAGRAM) Problem Statement: Write a program to input the length and width of the rectangle, and calculate and print the perimeter and area of rectangle. Nouns : length, width, rectangle, perimeter, area Verbs : print, calculate

30 UML EXAMPLE Methods (Operation) Attributes Rectangle - width: double -length : double + calcuArea():double + calcuPerimeter()double + print () void

31 Java Programming: From Problem Analysis to Program Design, 4e 31 Classes class : reserved word; collection of a fixed number of components Components: members of a class Members accessed by name Class categories/modifiers – private – protected – public

32 Accessibilities options – public – Accessible to all – private – Accessible to containing class – protected – Accessible to containing or derived classes In most cases: fields are private or protected, and methods are public. ACCESS MODIFIERS

33 Java Programming: From Problem Analysis to Program Design, 4e 33 Syntax The general syntax for defining a class is:

34 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 34 Declaring a Class with Java public class ClassName { // Attributes // Methods (services) } Methods (Services) Attributes ClassName - att 1 : dataType 1 -… - att i : dataType i + m 1 (…): dataType 1 +... + m j (…): dataType j

35 public class Rectangle { // Attributes private double width; private double length; // Methods (Operation) public double calcArea(){ return height*width;} public double calcPerimeter(){ return 2*(height + width);} public void print() { System.out.print(“The Area is ”+calcArea()); System.out.print(“The Perimeter is ”+calcPerimeter()); } Rectangle - width: double -length : double + calcuArea():double + calcuPerimeter()double + print () void

36 Java Programming: From Problem Analysis to Program Design, 4e 36 Syntax (continued) If a member of a class is a named constant, you declare it just like any other named constant If a member of a class is a variable, you declare it just like any other variable If a member of a class is a method, you define it just like any other method

37 Java Programming: From Problem Analysis to Program Design, 4e 37 Syntax (continued) If a member of a class is a method, it can (directly) access any member of the class— data members and methods - Therefore, when you write the definition of a method (of the class), you can directly access any data member of the class (without passing it as a parameter)

38 OBJECT ORIENTED PROGRAMMING CLASSES & OBJECTS

39 OBJECT STATE All objects of the same class have the same characteristics (attributes) and the same behavior (methods). Each object has a value for each instance attribute. The state of an object encompasses: all of the instance attributes of the object the current data values assigned to these attributes. When we talk about the current state of the object, we are really talking about the current values of its attributes. The values of instance attributes can change over time. A complete set of the specific values of these attributes forms a specific state of the object. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 39 Object: Course studentName courseCode Mohammed CSC 112

40 THE ANATOMY OF AN OBJECT An object has: reference (also called Object Identifier (OID)) A unique identifier provided by the Object System and that makes the object unique. It is acquired at birth and does not change during the life of the object. State Represents the data that the object contains. Behavior Represents the services (the methods) that the object may perform. The features of an object are its attributes and operations. an instance attribute is an element of the object state. an operation (method) is an element of the object behavior. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 40

41 Class Instantiation A class is a specification or design and an instance is a “real world” occurrence of the design Just as someone has to build a car from its engineering drawings before you can actually drive it, you must build an object of a class before you can perform the tasks the class describes. You can have as many instances as you like from a single class

42 OBJECT CREATION Creating objects is similar to declaring variables and can be done using the syntax:- Step 1 : First declare a variable of the given class. This variable is called instance variable or object reference variable. ClassName variableName ; Step 2: initialize the instance variable declared in 1 by assigning the newly created object to the instance variable. Just as with variable assignment or initialization. The syntax for initializing an object to an instance variable is: variableName = new ClassName(); Both step 1 and 2 may be combined within the same statement as following (declaration statement with initial value): ClassName variableName = new ClassName(); Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 42

43 Declaring & Instantiating Objects (Object Creation Example) class Course { // Instance attributes String studentName; String courseCode ; //some methods } public class client { public static void main(string[] args) { Course course1 = new Course (); Course course2 = new Course (); }

44 OBJECT CREATION Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 44 crs = ; Code State of Memory Course crs; A A C C crs A. A. The instance variable is allocated in memory. new Course( ) new Course ( ) B B B. B. The object is created C. C. The reference of the object created in B is assigned to the variable. Object: Course studentName courseCode crs Object: Course studentName courseCode

45 OBJECTS AND INSTANCE VARIABLES Once the Student class is defined, we can create several instances. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 45 Object: Course studentName courseCode Object: Course studentName courseCode course2 1 Course course1, course2; course1 = new Course( ); course2 = new Course( ); Instance variable Object reference Object state

46 INSTANCE VS. PRIMITIVE VARIABLES Primitive variables hold values of primitive data types. Instance variables hold references of objects: the location (memory address) of objects in memory. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 46

47 ASSIGNING OBJECTS’ REFERENCES TO THE SAME INSTANCE VARIABLE Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 47 Code State of Memory Course crs; crs = new Course( ); crs = new Course ( ); A A B B C C crs A. A. The variable is allocated in memory. B. crs B. The reference to the new object is assigned to crs. Course C. crs. C. The reference to another object overwrites the reference in crs. Course

48 ASSIGNING AN OBJECT REFERENCE FROM ONE VARIABLE TO ANOTHER Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 48 Code State of Memory Course crs1, crs2, crs1 = new Course( ); crs2 = crs1; A A B B C C A. A. Variables are allocated in memory. crs1 crs2 B. crs1 B. The reference to the new object is assigned to crs1. Course C. crs1 crs2. C. The reference in crs1 is assigned to crs2.

49 ASSIGNING AN OBJECT REFERENCE FROM ONE VARIABLE TO ANOTHER Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 49 Course crs1, crs2, crs1 = crs2; A A C C A. A. Variables are allocated in memory. crs1crs2 crs1 = new Course( ); crs2 = new Course( ); B B B. B. Variables are assigned references of objects. Course crs1crs2 C. crs2 crs1. C. The reference in crs2 is assigned to crs1. Course crs1crs2

50 ACCESSING INSTANCE ATTRIBUTES In order to access attributes of a given object: use the dot (.) operator with the object reference (instance variable) to have access to attributes’ values of a specific object. instanceVariableName. attributeName course1.StudentName= “Majed AlKebir“; course2.StudentName= “Fahd AlAmri “; Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 50 course1 Object: Course studentNameMajed AlKebir courseCode course2 Object: Course studentNameFahd AlAmri courseCode

51 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 51 class Course { // Instance attributes public String studentName; public String courseCode ; } public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.courseCode= new String(“CSC112“); course1.studentName= new String(“Majed AlKebir“); //Create and assign values to course2 course2 = new Course( ); course2.courseCode= new String(“CSC107“); course2.studentName= new String(“Fahd AlAmri“); System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); }

52 PRACTICAL HINT Class Course will not execute by itself It does not have method main CourseRegistration uses the class Course. CourseRegistration, which has method main, creates instances of the class Course and uses them. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 52

53 MESSAGE PASSING PRINCIPLE OR METHOD INVOCATION Information hiding prevent the data inside the object from being directly accessed by outsiders. Encapsulation allows objects to include the appropriate operations that could be applied on the data stored in the object. So, the data that an object stores would be accessed only through appropriate operations (methods). 53

54 MESSAGE PASSING PRINCIPLE OR METHOD INVOCATION Message passing is the principle that allows objects to communicate by exchanging messages. Passing a message to an object means ordering this object to execute a specific method. This is also called method invocation

55 MESSAGE PASSING PRINCIPLE OR METHOD INVOCATION Objects communicate through messages (invoking or calling methods of other objects) Methods: mostly public Fields: Private or protected You send messages to an object by making method calls. However, we need to create objects (instances) from classes first

56 import java.util.Scanner; class Course { // Instance attributes public String studentName; public String courseCode ; public Scanner input = new Scanner (System.in); // Methods public void enterDataFromKeyBoard() { System.out.println(“Enter Student Name:); studentName=input.next(); System.out.println(“Enter Course Code:); courseCode=input.next(); } // print content public void disply () { System.out.println(“The Student Name is : ”+studentName ); System.out.println(“The Course Code is : ”+courseCode); } Course +studentName: String +courseCode: String +studentNumber:int +input: Scanner + enterDataFromKeyBoard ():void + display():void

57 METHOD INVOCATION Invoking a method of a given object requires using: the instance variable that refers to this object. the dot (.) operator as following: instanceVariable.methodName(arguments) 57 public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.enterDataFromKeyBoard();course1.display(); //Create and assign values to course2 course2 = new Course( ); course2.enterDataFromKeyBoard();course2.display(); }

58 OBJECT ORIENTED PROGRAMMING CLASS METHODS & ATTRIBUTES

59 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 59 Declaring a Class with Java public class ClassName { // Attributes // Methods (services) } Methods (Services) Attributes ClassName - att 1 : dataType 1 -… - att i : dataType i + m 1 (…): dataType 1 +... + m j (…): dataType j

60 ATTRIBUTE An attribute is an abstraction of a single characteristic possessed by all objects of the same class. An attribute has a name unique within the class. There are two types of attributes: Class attributes (static variables) Independent of any object and their values are shared by all objects of the class. Instance attributes Dependent to the objects and their values are associated with and accessed through objects. Page 60

61 CLASS AND INSTANCE ATTRIBUTES Instance attributes (and methods) are: associated with an instance (object) of the class. and accessed through an object of the class. each object of the class has its own distinct copy of instance attributes (and methods) Class attributes (and methods): live in the class can also be manipulated without creating an instance of the class. are shared by all objects of the class. do not belong to objects’ states. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 61

62 CLASS ATTRIBUTES AND OBJECTS A class attribute is in one fixed location in memory. Every object of the class shares class attributes with the other objects. Any object of the class can change the value of a class attribute. Class attributes (and methods) can also be manipulated without creating an instance of the class. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 62

63 CLASS ATTRIBUTES DECLARATION The class attributes (and methods) are declared as instance attribute but with the static modifier in addition. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 63 ; public static int studentNumber ; Modifiers Data Type Name

64 CLASS ATTRIBUTES ACCESS Class attributes (and methods) can also be manipulated without creating an instance of the class. Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 64. Course. studentNumber = 0 ; Class Name Attribute Name

65 DECLARING INSTANCE ATTRIBUTES WITH JAVA Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 65 ; public String studentName ; Modifiers Data Type Name

66 EXAMPLE OF A CLASS DECLARATION WITH JAVA Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 66 public class Course { // Attributes public String studentName; public String courseCode ; // No method Members } Course. studentName= “Ahmed ” ; Course course1 = new Course( ); course1.studentName= “Ahmed ” ;

67 Introduction to OOP Dr. S. GANNOUNI & Dr. A. TOUIR Page 67 class Course { // attributes public String studentName; public String courseCode ; public static int studentNumber; } public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); Course.studentNumber = 1; course1.courseCode= “CSC112”; course1.studentName= “Majed AlKebir“; //Create and assign values to course2 course2 = new Course( ); Course.studentNumber ++; course2.courseCode= “CSC107”; course2.studentName= “Fahd AlAmri”; System.out.println(course1.studentName + " has the course “+ course1.courseCode + “ ” + course1.studentNumber); System.out.println(course2.studentName + " has the course “+ course2.courseCode + “ ” + course2.studentNumber); } Course +studentName: String +courseCode: String +studentNumber:int

68 CLASS ATTRIBUTES AND INSTANCE ATTRIBUTES Object: Course studentName CSC112 courseCode Object: Course studentName CSC107 courseCode course2 1 Majed AlKebir Fahd AlAmri studentNumber 2

69 DECLARING PRIVATE ATTRIBUTES 69 ; private String studentName ; Modifiers Data Type Name

70 EXAMPLE OF A CLASS WITH PRIVATE ATTRIBUTES 70 public class Course { // Attributes private String studentName; private String courseCode ; // No method Members } Course - studentName: String - courseCode: String

71 PUBLIC AND PRIVATE MODIFIERS Let’s consider a class X. Let’s consider Y a client class of X. Y is a class that uses X. Attributes (and methods) of X declared with the public modifier are accessible from instances of Y. The public modifier does not guarantee the information hiding. Attributes (and methods) of X declared with the private modifier are not accessible from instances of Y. The private modifier guarantee the information hiding. 71

72 72 Accessibility from Inside (the same class) All members of an instance are accessible from the instance itself. object:X public - Accessible - Inaccessible private

73 73 Accessibility from an Instance in another Class Only public members Are visible from outside. All else is hidden from Outside. :Y(client) Accessibility from The Client class. object:X public private - Accessible - Inaccessible

74 ACCESSIBILITY EXAMPLE 74 class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientService

75 75 class Course { // Data Member private String studentName; private String courseCode ; } public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.courseCode= “CSC112“; course1.studentName= “Majed AlKebir“; //Create and assign values to course2 course2 = new Course( ); course2.courseCode= “CSC107“; course2.studentName= “Fahd AlAmri“; System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); } Course - studentName: String - courseCode: String

76 HOW PRIVATE ATTRIBUTES COULD BE ACCESSED Private attributes are not accessible from outside. Except from objects of the same class. They are accessible: From inside: from the object containing the data itself. From objects of the same class. They are accessible from outside using accessor methods: Getters Setters 76

77 OBJECT ORIENTED PROGRAMMING CLASSES & OBJECTS CLASS METHODS

78 78 class Course { // Data Member private String studentName; private String courseCode ; } public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.courseCode= “CSC112“; course1.studentName= “Majed AlKebir“; //Create and assign values to course2 course2 = new Course( ); course2.courseCode= “CSC107“; course2.studentName= “Fahd AlAmri“; System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); } Course - studentName: String - courseCode: String

79 CLASS COMMON METHODS Accessor method (getters): to get information about an object Mutator methods (setters):to mutate (change) an object’s state Printing method: to specify how to print an object Constructor method: to initiate an object by sending its values as parameters

80 GETTERS Are operations performed by the object returning to outsiders data retrieved from the object state. Are services called from outside allowing to retrieve data from the object state. 80 The object point of view The user point of view object:X public private Getters :Y (Client) Data Getters are: Public With no parameters With return value

81 TEMPLATE FOR GETTERS 81 public class ClassName { private dataType1 attribute1;... private dataTypen attributen;... public dataType1 getAttribute1() { return attribute1; }... public dataTypen getAttributen() { return attributen; }... }

82 public int GetAge() { return age; } return type method name parameter list (empty in this case) start and end of method body (block) return statement access modifier GETTER EXAMPLE Because accessor methods have a return type they must have at least one return statement

83 SETTERS Are operations performed by the object allowing to receive and store in the object state the data provided by outsiders. Are services used by outsiders allowing to provide to the object the data that should be stored in the object state. 83 The object point of view The user point of view object:X public private Setters :Y (Client) Data Setters are: Public With 1 parameter With no return value

84 TEMPLATE FOR SETTERS 84 public class ClassName { private dataType1 attribute1;... private dataTypen attributen;... public void setAttribute1(dataType1 param){ attribute1 = param; }... public void setAttributen(dataTypen param) { attributen = param; }... }

85 85 public class Course { // Attributes private String studentName; private String courseCode ;... public String getStudentName() { return studentName; } public String getCourseCode() { return courseCode; }... public void setStudentName(String val) { studentName = val; } public void setCourseCode(String val) { courseCode = val; }

86 86 public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.setCourseCode(“CSC112“); course1.setStudentName(“Majed AlKebir“); //Create and assign values to course2 course2 = new Course( ); course2.setCourseCode(“CSC107“); course2.setStudentName(“Fahd AlAmri“); System.out.println(course1.getStudentName() + " has the course “ + course1.getCourseCode()); System.out.println(course2.getStudentName() + " has the course “ + course2.getCourseCode()); }

87 PASSING AN OBJECT TO A SETTER 87 Student owner;

88 class Person Name : string Age: int Sex: char GetName() GetAge() GetSex() obj1: Person name age sex john 25 M obj2: Person name age sex jane 22 F getName “john” getAge 22 – Methods getName, getAge can be called by other objects (not shown) to get or access attributes (called accessor methods) – Other methods can be defined, which change an object’s attributes (i.e. state) (called mutator methods) private public encapsulation EXAMPLE

89 PRINT Printing method: to specify how to print an object class Course { // Instance attributes public String studentName; public String courseCode ; // Methods // Attributes private String studentName; private String courseCode ; public String getStudentName() {return studentName;} public String getCourseCode() {return courseCode;} public void setStudentName(String val) {studentName = val;} public void setCourseCode(String val) {courseCode = val;} // print content public void disply () { System.out.println(getStudentName()+" has the course “ + getCourseCode()); }

90 90 public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.setCourseCode(“CSC112“); course1.setStudentName(“Majed AlKebir“); //Create and assign values to course2 course2 = new Course( ); course2.setCourseCode(“CSC107“); course2.setStudentName(“Fahd AlAmri“); course1.disply(); }

91 CLASS CONSTRUCTORS Constructors define the initial states of objects when they are created. ClassName x = new ClassName(); A class contains at least one constructor. A class may contain more than one constructor. 91

92 CONSTRUCTORS Constructor is a special method that gets invoked “automatically” at the time of object creation. Constructor is normally used for initializing objects with default values unless different values are supplied. Constructor has the same name as the class name. Constructor cannot return values. A class can have more than one constructor as long as they have different parameter (i.e., different input arguments syntax).

93 THE DEFAULT CLASS CONSTRUCTOR If no constructors are defined in the class, the default constructor is added by the compiler at compile time. The default constructor does not accept parameters and creates objects with empty states. ClassName x = new ClassName(); 93

94 CLASS CONSTRUCTORS DECLARATION The constructor name: a constructor has the name of the class. The parameters represent values that will be passed to the constructor for initialize the object state. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. Invoking: There is NO explicit invocation statement needed: When the object creation statement is executed, the constructor method will be executed automatically. 94 public ( ){ }

95 EXAMPLE OF A CONSTRUCTOR WITH NO-PARAMETER 95 Public class Person { String name; int age; // Constructor public Person(){ name = “ ”; age = 0;} } P1 = ; Code Person P1; new Person( ) A A C C B B State of Memory x A. A. The instance variable is allocated in memory. B. B. The object is created with initial state C. C. The reference of the object created in B is assigned to the variable. x Person age 0 “ ” Object: Kasree bast maquam 1 0 name Person age 0 “ ” name

96 CLASS WITH MULTIPLE CONSTRUCTORS 96 Public class Person { String name; int age; // Constructor public Person(){ name = “ ”; age = 0;} public Person(String n, int a ) { name = n; age = a; } P1 = new Person() P2 = new Person(“Ahmed”,27); Code Person P1, P2; A A State of Memory x A. A. The constructor declared with no-parameter is used to create the object Object: Kasree bast maquam 27 Ahmed B B y B. B. The constructor declared with parameters is used to create the object Person age 0 “ ” name age name

97 Constructor and Static attribute One of the most common example is to have a variable that could keep a count of how many objects of a class have been created. Note: Java creates only one copy for a static variable which can be used even if the class is never instantiated.

98 CONSTRUCTOR EXAMPLE Public class Person { string name; int age; public static int numofPerson=0; // Constructor public Person() { name = “ ”; age = 0; numofPerson++ } public Person( string n, int a) { name = n; age = a; numofPerson++; } public static void Main(string[] args) { Person P1 = new Person(); Person P2 = new Person (“ahmed”, 27); }

99 CLASS WITH MULTIPLE CONSTRUCTORS public static void Main(string[] args) { Person P1 = new Person(); Person P2 = new Person (“ahmed”, 27); } 99 P1 = new Person() P2 = new Person(“Ahmed”,27); Code Person P1, P2; A A State of Memory P1 Object: Kasree bast maquam 27 Ahmed B B P2 Person age 0 “ ” name age name 0 0 numofPerson A A 1 1 2 2 B B

100 ARRAYS OF OBJECTS Can use arrays to manipulate objects Example: create array named array1 with N objects of type T T[] array1 = new T[N] Can instantiate array1 as follows: for ( int j = 0; j <array1.length; j++) array1[j] = new T(); Java Programming: From Problem Analysis to Program Design, 4e 100

101 ARRAY OF STRING OBJECTS String[] nameList = new String[5]; nameList[0] = "Amanda Green"; nameList[1] = "Vijay Arora"; nameList[2] = "Sheila Mann"; nameList[3] = "Rohit Sharma"; nameList[4] = "Mandy Johnson"; Java Programming: From Problem Analysis to Program Design, 4e 101

102 ARRAY OF STRING OBJECTS (CONTINUED) Java Programming: From Problem Analysis to Program Design, 4e 102

103 CLOCK[] ARRIVALTIMEEMP = NEW CLOCK[100]; Java Programming: From Problem Analysis to Program Design, 4e 103 Arrays of Objects (continued)

104 INSTANTIATING ARRAY OBJECTS Java Programming: From Problem Analysis to Program Design, 4e 104 for (int j = 0; j < arrivalTimeEmp.length; j++) arrivalTimeEmp[j] = new Clock();

105 Java Programming: From Problem Analysis to Program Design, 4e 105 arrivalTimeEmp[49].setTime(8, 5, 10); Instantiating Array Objects (continued)


Download ppt "OBJECT ORIENTED PROGRAMMING INTRODUCTION. WHAT IS OBJECT-ORIENTATION ALL ABOUT? Principles and techniques for system modeling which: Aim to produce a."

Similar presentations


Ads by Google