Classes and Objects. Object vs. Class Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2  A class could be considered as a set of objects having.

Slides:



Advertisements
Similar presentations
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Advertisements

1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Methods. int month; int year class Month Defining Classes A class contains data declarations (static and instance variables) and method declarations (behaviors)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
Information Hiding Chapter 5: Classes and Objects in Depth.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.
Class attributes Chapter 3: Introduction to Classes and Objects.
1 Chapter 7 User-Defined Methods Java Programming from Thomson Course Tech, adopted by kcluk.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Introduction to methods Chapter 5: Classes and Objects in Depth.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
Chapter Chapter 4 Defining Your Own Classes Part 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Methods
Chapter 2: Java Fundamentals Java Program Structure.
Objects and Instance attributes and variables Chapter 3: Introduction to Classes and Objects.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Develop Instantiable classes (continue). Exam 1 – section 02 Avg = 131 (87%). Max: 148.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Why Programmer-Defined Classes Using just the String,
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Chapter 10 METHODS AND CONSTRUCTORS 1. Accessing Objects  Referencing the object’s data: objectReference.data myCircle.radius  calling the object’s.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
BCS 2143 Object Oriented Programming Defining Your Own Classes (Part 1)
Classes and Methods Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall 2014.
Java Fundamentals 3 Input and Output statements. Standard Output Window Using System.out, we can output multiple lines of text to the standard output.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
RECITATION 4. Classes public class Student { } Data Members public class Student { private String name; public String id; }
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
SEEM Java – Basic Introduction, Classes and Objects.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
CS1201: Programming Language 2 Classes and objects.
Classes and Objects. Object Software objects are modeled after real-world objects in that they, too, have state and behavior. A software object maintains.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 4 Defining Your Own Classes Part 1 Animated Version.
Classes and Objects. How can one design a program?  Top-down structured design: uses algorithmic decomposition where each module denotes a major step.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Class Everything in Java is in a class. The class has a constructor that creates the object. If you do not supply a constructor Java will create a default.
OBJECT ORIENTED PROGRAMMING INTRODUCTION. WHAT IS OBJECT-ORIENTATION ALL ABOUT? Principles and techniques for system modeling which: Aim to produce a.
Dr. Majed Abdouli © Objects and Classes 1 Dr. Majed Abdouli © 2015, adapted from Liang, Introduction to Java Programming, Eighth Edition, (c) 2011.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 7 User-Defined Methods.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 7 User-Defined Methods.
Object Oriented Programming
CS1201: Programming Language 2
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.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Defining Your Own Classes Part 1
Defining Your Own Classes
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Chapter 5: Classes and Objects in Depth
Classes and Objects.
Chapter 5: Classes and Objects in Depth
CS1201: Programming Language 2
Chapter 5: Classes and Objects in Depth
ITE “A” GROUP 2 ENCAPSULATION.
Previous Lecture: Today’s Lecture: Reading (JV):
Presentation transcript:

Classes and Objects

Object vs. Class Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 2  A class could be considered as a set of objects having the same characteristics and behavior.  An object is an instance of a class.

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

Declaring Attributes With Java Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 4 ; public String studentName ; Modifiers Data Type Name

Example of a Class Declaration with Java Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 5 public class Course { // Attributes public String studentName; public String courseCode ; // No method Members }

Object Creation Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 6 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

Object Creation Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 7 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

Instance VS. Primitive Variables Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 8  Primitive variables hold values of primitive data types.  Instance variables hold references of objects: the location (memory address) of objects in memory.

Assigning Objects’ References to the same Instance Variable Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 9 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

Assigning an Object Reference From One Variable to Another Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 10 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.

Assigning an Object Reference From One Variable to Another Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 11 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 A. A. Variables are assigned references of objects. Course crs1crs2 C. crs2 crs1. C. The reference in crs2 is assigned to crs1. Course crs1crs2

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= “Sara AlKebir“; course2.StudentName= “Maha AlSaad“; Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 12 course1 Object: Course studentNameMajed AlKebir courseCode course2 Object: Course studentNameFahd AlAmri courseCode

Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 13 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(“Sara AlKebir“); //Create and assign values to course2 course2 = new Course( ); course2.courseCode= new String(“CSC107“); course2.studentName= new String(“Maha AlSaad“); System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); }

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 OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 14

output

Modifiers Static Public+Private -Protected #

Static Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 18  It used to define class 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. ; public static int studentNumber ; Modifiers Data Type Name

Class Attributes Access Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 19  Class attributes (and methods) can also be manipulated without creating an instance of the class.. Course. studentNumber = 0 ; Class Name Attribute Name

Introduction to OOPDr. S. GANNOUNI & Dr. A. TOUIRPage 20 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= new String(“CT1513“); course1.studentName= new String(“Sara AlKebir“); //Create and assign values to course2 course2 = new Course( ); Course.studentNumber ++; course2.courseCode= new String(“CSC107“); course2.studentName= new String(“Maha AlSaad “); System.out.println(course1.studentName + " has the course “+ course1.courseCode + “ ” + course1.studentNumber); System.out.println(course2.studentName + " has the course “+ course2.courseCode + “ ” + course2.studentNumber); }

output

public and private modifiers 22  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.

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

24 Accessibility from an Instance of 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

25 Accessibility from an Instance of the same Class If a member is accessible from an instance, it is also accessible from other instances of the same class. two:X Accessibility from The Client class. one:X public - Accessible - Inaccessible private

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. 26 Methods (Services) Attributes ClassName - att 1 : dataType 1 -… - att i : dataType i + m 1 (…): dataType m j (…): dataType j

Declaring Private Attributes 27 ; private String studentName ; Modifiers Data Type Name

Example of a Class with Private attributes 28 public class Course { // Attributes private String studentName; private String courseCode ; // No method Members } ClassName - studentName: String - courseCode: String

29 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= “Ct1513“; course1.studentName= “Sara AlKebir“; //Create and assign values to course2 course2 = new Course( ); course2.courseCode= “CSC107“; course2.studentName= “Maha AlSaad“; System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); }

Accessibility Example 30 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

Methods

Method Declaration 32  Method declaration is composed of:  Method header.  Method body { }

Method Declaration (cont.) 33 public void setOwnerName ( String name ) { ownerName = name; } Method body Modifier Return Type Method Name Parameters ( ){ }

Example of Methods with No-Parameters and No-Return value 34 import java.util.Scanner; public class Course { // Attributes private String studentName; private String courseCode ; private static Scanner input = new Scanner(System.in); //Class att. // Methods public void enterDataFromKeyBoard() { System.out.print (“Enter the student name: ”); studentName = input.next(); System.out.print (“Enter the course code: ”); courseCode = input.next(); } public void displayData() { System.out.println (“The student name is: ” + studentName); System.out.println (“The the course code is: ”+ courseCode); }

Method Invocation 35  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) 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(); }

Method Invocation Execution Schema 36 class Client { public static void main(String[] arg) { X obj = new X(); // Block statement 1 obj.method(); // Block statement 2 }... } The client class X {... public void method() { // Method body }... } The client Block statement 1 executes Block statement 2 starts The method Invocation The method body starts Passing Parameters if exist The method body finishes Return result if any

Example of a Method with Return value 37 public class Student { // Attributes private String studentName; private int midTerm1, midTerm2, lab, final ; // Methods public int computeTotalMarks() { int value = mid1 + mid2 + lab + final; return value; } public class TestStudent { public static void main (String [] args) { Student st = new Student(); int total; … total = st.computeTotalMarks(); System.out.println(total); }

Template for Methods with Return value 38 public class ClassName { // Attributes... // Methods... public returnType methodName(…) { returnType variableName; // 1 - calculate the value to return // 2 - assign the value to variableName return variableName; } public class ClientClass { public static void main (String [] args) { ClassName instanceVariable = new ClassName(); returnType receivingVaraiable;... receivingVaraiable = instanceVariable.methodName(…);... }

Arguments and Parameters 39  An argument is a value we pass to a method.  A parameter is a placeholder in the called method to hold the value of the passed argument. class Sample { public static void main(String[] arg) { Account acct = new Account();... acct.add(400);... }... } Argument (Actual Parameter) class Account {... public void add(double amt) { balance = balance + amt; }... } Formal parameter

Programming Example: Largest Number 40  Input: set of 10 numbers  Output: largest of 10 numbers  Solution  Get numbers one at a time  Method largest number: returns the larger of two numbers  For loop: calls method largest number on each number received and compares to current largest number Java Programming: From Problem Analysis to Program Design, 4e

Solution: Largest Number 41 public static double larger (double x, double y) { if (x >= y) return x; else return y; } public static void main(String[] args) { double num; double max; int count; System.out.println("Enter 10 numbers."); num = console.nextDouble(); max = num; for (count = 1; count < 10; count++) { num = console.nextDouble(); max = larger(max, num); } System.out.println("The largest number is " + max); Java Programming: From Problem Analysis to Program Design, 4e

42 Sample Run: Largest Number Java Programming: From Problem Analysis to Program Design, 4e Sample Run Enter 10 numbers: The largest number is 88.55

43 Information Hiding Getter, Setter and Constructor

How Private Attributes could be Accessed 44  Private attributes are accessible from outside using accessor operations.  Getters  Setters

45 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= “CT1513“; course1.studentName= “Sara AlKebir“; //Create and assign values to course2 course2 = new Course( ); course2.courseCode= “CT1413“; course2.studentName= “Maha AlSaad“; System.out.println(course1.studentName + " has the course “+ course1.courseCode); System.out.println(course2.studentName + " has the course “+ course2.courseCode); }

Template for Getters 46 public class ClassName { private dataType1 attribute1;... private dataTypen attributen;... public dataType1 getAttribute1() { return attribute1; }... public dataTypen getAttributen() { return attributen; }... }

Template for Setters 47 public class ClassName { private dataType1 attribute1;... private dataTypen attributen;... public void setAttribute1(dataType1 param){ attribute1 = param; }... public void setAttributen(dataTypen param) { attributen = param; }... }

48 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; }

49 public class CourseRegistration { public static void main(String[] args) { Course course1, course2; //Create and assign values to course1 course1 = new Course( ); course1.setCourseCode(“CT1513“); course1.setStudentName(“Sara AlKebir“); //Create and assign values to course2 course2 = new Course( ); course2.setCourseCode(“CT1413“); course2.setStudentName(“Maha AlSaad“); System.out.println(course1.getStudentName() + " has the course “ + course1.getCourseCode()); System.out.println(course2.getStudentName() + " has the course “ + course2.getCourseCode()); }

Class Constructors 50  A class is a blueprint or prototype from which objects of the same type are created.  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.

The Default Class Constructor 51  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();

Class Constructors Declaration 52  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. public ( ){ }

Example of a Constructor with No-Parameter 53 public class Kasree { private int bast; private int maquam; public Kasree() { bast = 0; maquam =1; }... } x = ; Code Kasree x; new Kasree( ) new Kasree ( ) 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 Object: Kasree bast maquam 1 0 Object: Kasree bast maquam 1 0

Class with Multiple Constructors 54 public class Kasree { private int bast; private int maquam; public Kasree() { bast = 0; maquam =1; } public Kasree(int a, int b) { bast = a; if (b != 0) maquam = b; else maquam = 1; }... } x = new Kasree() y = new Kasree(4, 3); Code Kasree x, y; A A State of Memory x A. A. The constructor declared with no-parameter is used to create the object Object: Kasree bast maquam 1 0 Object: Kasree bast maquam 3 4 B B y B. B. The constructor declared with parameters is used to create the object

Copy Constructor  Makes a new copy of an object  Used in some object declarations, when an object is used as a parameter to the constructor of a class of the same type:

Class with copy Constructors 56 public class Kasree { private int bast; private int maquam; public Kasree() { bast = 0; maquam =1; } public Kasree(Kasree k) { bast = k.bast; maquam =k. maquam; } x = new Kasree() y = new Kasree(x); Code Kasree x, y; A A State of Memory x A. A. The constructor declared with no-parameter is used to create the object Object: Kasree bast maquam 1 0 Object: Kasree bast maquam 1 0 B B y B. B. The copy constructor declared with refrence parameters is used to create the object k