Object-Oriented Programming Concepts

Similar documents

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

CHAPTER 7 OBJECTS AND CLASSES

Example: Fibonacci Numbers

- Aggregation - UML diagram - Self-Referential Classes - Generisity

Lecture 7: Classes and Objects CS2301

Recursion 1. Recursion is the process of defining something in terms of itself.

CHAPTER 7 OBJECTS AND CLASSES

Object Oriented Programming. Week 1 Part 3 Writing Java with Eclipse and JUnit

CSEN401 Computer Programming Lab. Topics: Introduction and Motivation Recap: Objects and Classes

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Lecture 11: Intro to Classes

ITI Introduction to Computing II

Chapter 6 Introduction to Defining Classes

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

ECOM 2324 COMPUTER PROGRAMMING II

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

BBM 102 Introduction to Programming II Spring 2017

( &% class MyClass { }

Object Oriented Programming in C#

ITI Introduction to Computing II

Object Oriented Programming

Object Oriented Modeling

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Java Programming. U Hou Lok. Java Aug., Department of Computer Science and Information Engineering, National Taiwan University

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Lecture 12: Classes II

Classes and Objects. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

Chapter 8 Objects and Classes Dr. Essam Halim Date: Page 1

Building Java Programs

Selected Questions from by Nageshwara Rao

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Object-Oriented Programming Concepts

The return Statement

Java Classes & Primitive Types

Creating an object Instance variables

Object-Oriented Programming (Java)

UFCE3T-15-M Object-oriented Design and Programming

Java Classes & Primitive Types

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Lecture 3. Lecture

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Introduction to Programming Using Java (98-388)

Programming II (CS300)

Lecture 06: Classes and Objects

BM214E Object Oriented Programming Lecture 8

Chapter 4 Defining Classes I

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Lecture 6 Introduction to Objects and Classes

CS111: PROGRAMMING LANGUAGE II. Lecture 1: Introduction to classes

Instance Members and Static Members

Chapter 3 Classes. Activity The class as a file drawer of methods. Activity Referencing static methods

Chapter 4: Writing Classes

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Computer Science II (20082) Week 1: Review and Inheritance

Lecture 18 Tao Wang 1

Chapter 9 Objects and Classes. Liang, Introduction to Java Programming, Eleventh Edition, (c) 2017 Pearson Education, Inc. All rights reserved.

Recommended Group Brainstorm (NO computers during this time)

Programming in the Large II: Objects and Classes (Part 1)

CS 170, Section /3/2009 CS170, Section 000, Fall

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Java Object Oriented Design. CSC207 Fall 2014

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

2. The object-oriented paradigm!

Building Java Programs

Object Oriented Programming

Anatomy of a Class Encapsulation Anatomy of a Method

Computer Science II (20073) Week 1: Review and Inheritance

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

CS1004: Intro to CS in Java, Spring 2005

Object Oriented Programming

Principles of Object Oriented Programming. Lecture 4

CH. 2 OBJECT-ORIENTED PROGRAMMING

Table of Contents Date(s) Title/Topic Page #s. Chapter 4: Writing Classes 4.1 Objects Revisited

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Chapter 8 Objects and Classes. Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Inheritance Motivation

Important Java terminology

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS304 Object Oriented Programming Final Term

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Comments are almost like C++

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Java and OOP. Part 2 Classes and objects

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

OO Programming Concepts

inside: THE MAGAZINE OF USENIX & SAGE August 2003 volume 28 number 4 PROGRAMMING McCluskey: Working with C# Classes

Assignment 1 due Monday at 11:59pm

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Objects and Classes: Working with the State and Behavior of Objects

Transcription:

Object-Oriented Programming Concepts Object-oriented programming מונחה עצמים) (תכנות involves programming using objects An object ) represents (עצם an entity in the real world that can be distinctly identified For example, a student, a desk, a circle, a button can all be viewed as objects An object has a unique identity ייחודית),(זהות state, and behaviors The state of (מצב) an object consists of a set of data fields (also known as properties) with their current values The behavior of (התנהגות) an object is defined by a set of methods 1

Objects-examples Robot - properties Student properties? lecturer properties? 2

) זהות ייחודית ( identity An object has : unique ) מצב) state ) התנהגות ( behaviors state(attributes) consists of a set of data fields (properties) with their current values behavior(operations) of an object is defined by a set of methods data field 1 data field m method 1 State (Properties) radius = 5 findarea() Data field, State Properties Method, Behavior Behavior method n (A) A generic object (B) An example of circle object 3

Classes - definitions In the real world, you'll often find many individual objects all of the same kind There may be thousands of other bicycles in existence, all of the same make and model Each bicycle was built from the same set of prototype components and (אבטיפוס) therefore contains the same In object-oriented terms, we say that your bicycle is an instance מופע) )of the class of (מחלקה) objects known as bicycles A class is the prototype from which individual objects are created 4

Classes - examples Classes( מחלקות ) examples: People,books,dogs,cats,cars,airplanes,trains, etc ) מופע של מחלקה) Instance of a class You, your parents, the book you are reading, the car you drive Example: Car class : Property names Method Names model startengine year stopengine Color accelerate 5

Instance of a class Class Name: Student A class template Data Fields: name is Methods: takecourse Student Object 1 Data Fields: Student Object 2 Data Fields: Student Object 3 Data Fields: name is Kerem David name is Onur Ronit Ronit name is Meltem Vered Three objects of the Student class Instances of the class Student A class is used to define an object The state (consists of a set of data fields) defines the object, and the behavior defines what the object does 6

Instance of a class - example 7

Java Classes Classes (מחלקות) are constructs that define objects of the same type (Building plan prototype - of similar objects) ) פעולות ( methods to define data fields and (משתנים) A Java class uses variables to define behaviors public class Point private double x; private double y; public void move(double dx, double dy) public void printpoint() // rest methods Class variables (properties) Class methods 8

Access Specifiers ) הכמסה ( encapsulation One of the techniques in OOP is It concerns the hiding of data in a class and making this class available only through methods Java allows you to control access to classes, methods, and variables via ) הרשאות גישה ( specifiers access public ( גישה פומבית ) classes, methods, and variables can be accessed from everywhere The private ( גישה פרטית ) keyword denotes that the variable (or method) is hidden from view of any other class public class Point private double x; // x cannot be accessed by any class except class Point private double y; // y cannot be accessed by any class except class Point 9

Objects-creating A variable can hold a primitive value or a reference to an object( הפניה ) A variable that serves as an object reference must be declared A class is used to define an object, and the class name can be thought of as the type of an object To create an object we use the new operator and the act ) יצירת אובייקט) of creating an object is called instantiation For example : Point p1 = new Point(); Name Type Memory Address p1 Point 3000 Point x = 00 y = 00 default values An object reference variable stores the memory address of an object 10

Constructors A class provides a special type of methods, known as constructors, which are invoked to construct objects from the class Constructor ( פעולה בונה ) is a special kind of methods that are invoked to perform initializing actions For example : Point p2 = new Point(35,2,4); Name Type Memory Address p2 Point 2000 Point x = 35 y = 24 Constructors must have the same name as the class itself 11

Constructors - example public class Point private double x; private double y; public Point(double x, double y) public void printpoint() // rest methods Constructors must have the same name as the class itself Constructors do not have a return type not even void 12

Constructors implementation public class Point private double x; private double y; Class variables (data fields) public Point(double x, double y) thisx=x; thisy=y; The this keyword is required is when a method argument or a local variable in a method has the same name as one of the data fields of the class 13

Constructor without parameters public Point( ) thisx = 75; thisy = 154; Point p3 = new Point( ); Choice 1 Choice 2 public Point( ) Name Type Memory Address p3 Point 1500 Point x = 75 y = 154 Point x = 00 y = 00 14

Default Constructor A class may be declared without constructors In this case, a default constructor with an empty body is implicitly declared in the class This constructor, called a,( פעולה בונה ברירת מחדל) default constructor is provided automatically from Java compiler only if no constructors are explicitly declared in the class The default constructor initializes all instance variables to default value (zero for numeric types, false for booleans) 15

Accessing a class variables Accessing a class variable through the class by specifying the name of the class, followed by a dot operator, followed by the name of the variable For example: Point p1 = new Point(); Point p2 = new Point(); p1x = 25; p1y = - 39; p2x = 10; p2y = p1y; Systemoutprintln( p1= + p1x +, + p1y ); Class variables can be initialized by an assignment statement This would produce following result: p1=25,-39 16

Accessing the methods of an object public class Circle private double x, y; // The coordinates of the // center of circle private double r; // The radius of circle // Methods that print the circumference and // return the area of the circle public void circumference( ) Systemoutprintln( 2 * 314 * r); public double area() return 314 * r * r; Circle c = new Circle( ); cx = 20; cy = 20; cr = 10; double a = carea( ); ccircumference( ); file testcirclejava This is why it is called "objectoriented" programming; the object is the focus here, not the method call This is probably the single most important feature of the object-oriented paradigm To access the methods of an object, we use the same syntax as accessing the data of an object We use an object reference to invoke an object's method file Circlejava 17

Differences between Variables of Primitive Data Types and Object Types Primitive type int i = 1 i 1 Created using new Circle() Object type Circle c c reference c: Circle radius = 1 Reference variables are created using defined constructors of the classes They are used to access objects These variables are declared to be of a specific type that cannot be changed Class objects, and various type of array variables come under reference data type Default value of any reference variable is null: a reference that does not currently point to an object 18

Referenced Data Fields The data fields can be of reference types For example: the following Student class contains a data field name of the String type and a data field grades of the integer array type public class Student private String name; // name has default value null private int age; // age has default value 0 private boolean ismemberstudcomunity; // default value false private int [ ] grades; // student s grades array has default value null private char gender; // c has default value '\u0000' 19

Copying Variables of Primitive Data Types and Object Types Primitive type assignment i = j Before: i 1 After: i 2 Objects in Java are referred using reference types, and there is no direct way to copy the contents of an object into a new object j 2 j 2 The assignment of one reference to another merely creates another reference to the same object c1 c2 Before: Object type assignment c1 = c2 After: c1 c2 c1: Circle radius = 5 C2: Circle radius = 9 c1: Circle radius = 5 C2: Circle radius = 9 20

Garbage collection As shown in the previous slide, after the assignment statement c1 = c2, c1 points to the same object referenced by c2 The object previously referenced by c1 is no longer referenced This object is known as garbage When the last reference to an object is lost, the object becomes a candidate for garbage collection ) אספן זבל ( collector Java performs automatic garbage by periodically reclaiming the memory space occupied by these object 21

Objects As Parameters file Pointjava file testpointsjava public class Point private double x; private double y; public boolean isegual(point m) return (mx == thisx && my == thisy) public void printpoint( ) Systemoutprintln( x= + thisx+ y= + thisy); // rest methods public static void main(string[ ] args) Point p1=new Point(20,30); Point p2=new Point(20,30); p1printpoint( ); p2printpoint( ); if (p1isequal(p2)) Systemoutprintln( YES ); else Systemoutprintln( NO ); This program generates the following output: x=20 y= 30 x=20 y=30 YES 22

Copy Constructor We can define multiple constructors in the class, with each one having a different argument list : constructor without parameter list, constructor with parameter list and copy constructor ( פעולה בונה מעתיקה ) with reference type parameter public class Point private double x; private double y; public Point(double x, double y) thisx=x; thisy=y; public Point( ) thisx=50; thisy=30; In java method overloading ( (העמסה means creating more than a single method with same name with different parameters In class Point three methods are created with the same name public Point( Point p) thisx=px; thisy=py; // rest class Point methods 23

Copy Constructor - example public static void main(string[ ] args) Point p1=new Point(20,30); Point p2=new Point(p1); p1printpoint( ); p2printpoint( ); This program generates the following output: x = 20 y = 30 x = 20 y = 30 Point Point p1 x y p2 x y 20 30 20 30 Two different instances of the Point object 24

tostring method The Java tostring() method is used when we need a string representation of an object This method is defined in Object class public class Point private double x; private double y; // constructor methods public String tostring( ) String str = ( x= + thisx+ y= + thisy); return str; // rest methods public static void main(string[ ] args) Point p1=new Point(20,30); Point p2=new Point(40,50); String s = p1tostring ( ); Systemoutprintln(s); // Systemoutprintln(p1toString()); Systemoutprintln(p2); This program generates the following output: x=20 y= 30 x=40 y=50 25

getter/setter methods Getter and setter methods are used to retrieve and manipulate private variables in a different class The difference between getter and setter methods is obvious: a getter method gets the value, a setter method sets the value The reason to use is because of the principle of information hiding ( הסתרת מידע ) - classes should not reveal their innards to the outside world This is the most important feature of the object-oriented programming 26

getter/setter methods - example public class Point private double x; private double y; // constructor methods public double getx( ) return thisx; public double gety( ) return thisy; public void setx(double x) thisx=x; public void sety(double y) thisy=y; // rest methods public static void main(string[ ] args) Point p1=new Point(20,30); Systemoutprintln(p1toString()); Systemoutprint( Enter the x value ); double newx = readernextdouble(); p1setx(newx); Systemoutprint( Enter the y value ); double newy = readernextdouble(); p1sety(newy); Systemoutprintln(p1toString()); This program generates the following output: x=20 y= 30 Enter the x value 40 Enter the y value 50 x=40 y= 50 27

Class variables - definition When a number of objects are created from the same class definition, they each have their own distinct copies of ) תכונות מופע ( variables instance For example : Each Point object has its own values for x and y coordinates variables, stored in different memory locations Sometimes, we want to have variables that are common to all objects This is accomplished with the static modifier Fields that have the static modifier in their declaration are (תכונות מחלקה) called static fields or class variables Any object can change the value of a class variable 28

Class variables - implementation public class Point private double x; private double y; private static int numpoints = 0; // constructor public Point(double x, double y) thisx = x; thisy = y; ++numpoints; // rest methods Coordinates - not static, thus not shared among instances of Point Keeps track of the number of Point objects created Since it is static, all Point objects share this variable Increment numpoints to tell anyone that we have another instance of this class 29

Class variables - example Every instance of the class shares a class variable, which is in one fixed location in memory numpoints 3 Point x y 20 30 Point x y 40 50 p1 p2 public static void main(string[ ] args) Point p1=new Point(20,30); Point p2=new Point(40,50); Point p3=new Point(60,70); Point x y 60 70 p2 30

Constants The static modifier, in combination with the final modifier, is also used to define constants The final modifier indicates that the value of this field cannot change For example: the following variable declaration defines a constant named PI static final double PI = 3141592653589793; Constants defined in this way cannot be reassigned By convention, the names of constant values are spelled in uppercase letters 31

Class (static) methods - definition The Java programming language supports class (static) methods as well as static variables Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class A common use for static methods is to access static fields For example, we could add a static method to the Point class to access the numpoints static field : 32

Class (static) methods example 1 public class Point private double x; private double y; private static int numpoints = 0; // constructors public static int getnumpoints( ) return PointnumPoints; // rest methods public static void main(string[] args) Systemoutprintln("Num of points : "+PointgetNumPoints()); Point p1=new Point(20,30); Systemoutprintln("Num of points : "+PointgetNumPoints()); Point p2=new Point(30,40); Systemoutprintln("Num of points : "+PointgetNumPoints()); This program generates the following output: Num of points : 0 Num of points : 1 Num of points : 2 NOTE : class method can be invoked with the class name, without the need for creating an instance of the class 33

Class (static) methods example 2 public class TestPoint public static int PointsNumber() External method return PointgetNumPoints(); public static void main(string[ ] args) Systemoutprintln("Num of points is: "+PointsNumber()); Point p1=new Point(20,30); Systemoutprintln("Num of points is: "+PointsNumber()); Point p2=new Point(30,40); Systemoutprintln("Num of points is: "+PointsNumber()); This program generates the following output: Num of points is: 0 Num of points is: 1 Num of points is: 2 Main method 34