object-oriented programming concepts - bguipc131/wiki.files/class_java_7.pdfobject-oriented...

34
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. Object-Oriented Programming Concepts 1

Upload: others

Post on 11-Jul-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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.

Object-Oriented Programming Concepts

1

Page 2: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Objects-examples

Student – properties ? Robot - properties lecturer – properties ?

2

Page 3: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

An object has : unique identity ( זהות ייחודית )

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

method n

data field m

method 1

(A) A generic object

...

...

State

(Properties)

Behavior

radius = 5

findArea()

Data field, State

Properties

Method,

Behavior

(B) An example of circle object

3

Page 4: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

.and therefore contains the same components(אבטיפוס)

• 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

Page 5: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

• 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

Classes - examples

5

Page 6: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Instance of a class

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.

Class Name: Student

Data Fields:

name is _______

Methods:

takeCourse

Student Object 1

Data Fields:

name is Kerem

Student Object 2

Data Fields:

name is Onur

Student Object 3

Data Fields:

name is Meltem

A class template

Three objects of

the Student class

David Ronit Vered

Instances of the class Student

Ronit

6

Page 7: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Instance of a class - example

7

Page 8: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Java Classes Classes (מחלקות) are constructs that define objects of the same type. (Building

plan – prototype - of similar objects).

A Java class uses variables (משתנים) to define data fields and methods ( פעולות )

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

Page 9: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Access Specifiers One of the techniques in OOP is encapsulation ( הכמסה ).

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

access specifiers ( הרשאות גישה ).

● 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

Page 10: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

y = 0.0

default

values

An object reference variable stores the memory address of an object 10

Page 11: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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(3.5,2,4);

• Constructors must have the same name as the class itself.

Name Type Memory Address

p2 Point 2000

Point

x = 3.5

y = 2.4

11

Page 12: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

Page 13: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Constructors – implementation

public class Point

{

private double x;

private double y;

public Point(double x, double y)

{

this.x=x;

this.y=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.

Class variables (data fields)

13

Page 14: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Constructor without parameters

public Point( )

{

this.x = 7.5;

this.y = 15.4;

}

Name Type Memory Address

p3 Point 1500

Point

x = 7.5

y = 15.4

public Point( )

{

}

Point

x = 0.0

y = 0.0

Point p3 = new Point( );

Choice 1 Choice 2

14

Page 15: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

Page 16: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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();

p1.x = 2.5;

p1.y = - 3.9;

p2.x = 10;

p2.y = p1.y;

System.out.println( “p1=“ + p1.x + “,“ + p1.y );

Class variables can be initialized by an

assignment statement.

This would produce following result: p1=2.5,-3.9 16

Page 17: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Accessing the methods of an object

To access the methods of an object, we use the same syntax

as accessing the data of an object

This is why it is called "object-oriented" programming;

the object is the focus here, not the method call. This is probably

the single most important feature of the object-oriented paradigm.

We use an object reference to invoke an

object's method file

testCircle.java

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

{ System.out.println( 2 * 3.14 * r); }

public double area()

{ return 3.14 * r * r; }

}

Circle c = new Circle( );

c.x = 2.0;

c.y = 2.0;

c.r = 1.0;

double a = c.area( );

c.circumference( ); file

Circle.java

17

Page 18: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Differences between Variables of Primitive Data Types and Object Types

1 Primitive type int i = 1 i

Object type Circle c c reference

Created using new Circle()

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

Page 19: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

Page 20: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Copying Variables of Primitive Data Types and Object Types

i

Primitive type assignment i = j

Before:

1

j

2

i

After:

2

j

2

c1

Object type assignment c1 = c2

Before:

c2

c1

After:

c2

c1: Circle

radius = 5

C2: Circle

radius = 9

c1: Circle

radius = 5

C2: Circle

radius = 9

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.

The assignment of one

reference to another merely

creates another reference to

the same object.

20

Page 21: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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.

● Java performs automatic garbage collector ( אספן זבל )

by periodically reclaiming the memory space occupied

by these object.

21

Page 22: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Objects As Parameters

public class Point

{

private double x;

private double y;

public boolean isEgual(Point m)

{

return (m.x == this.x && m.y == this.y)

}

public void printPoint( )

{

System.out.println( “x=“ + this.x+ ” y=“ + this.y);

}

// rest methods

public static void main(String[ ] args)

{

Point p1=new Point(2.0,3.0);

Point p2=new Point(2.0,3.0);

p1.printPoint( );

p2.printPoint( );

if (p1.isEqual(p2))

System.out.println( “YES“ );

else

System.out.println( “NO“ );

}

This program generates the following output:

x=2.0 y= 3.0

x=2.0 y=3.0

YES

file testPoints.java file Point.java

22

Page 23: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

this.x=x;

this.y=y; }

public Point( ) {

this.x=5.0;

this.y=3.0; }

public Point( Point p) {

this.x=p.x;

this.y=p.y; }

// rest class Point methods

In class Point three methods are created with the same name.

In java method overloading ( העמסה) means creating more than a single method with same name with different parameters.

23

Page 24: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Copy Constructor - example

public static void main(String[ ] args)

{

Point p1=new Point(2.0,3.0);

Point p2=new Point(p1);

p1.printPoint( );

p2.printPoint( );

}

This program generates the following

output:

x = 2.0 y = 3.0

x = 2.0 y = 3.0

Point

x y

2.0 3.0

p1

Point

x y

2.0 3.0

p2

Two different instances of the Point object 24

Page 25: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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=“ + this.x+ ” y=“ + this.y);

return str;

}

// rest methods

public static void main(String[ ] args)

{

Point p1=new Point(2.0,3.0);

Point p2=new Point(4.0,5.0);

String s = p1.toString ( );

System.out.println(s);

// System.out.println(p1.toString());

System.out.println(p2);

}

This program generates the following output:

x=2.0 y= 3.0

x=4.0 y=5.0 25

Page 26: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

Page 27: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

getter/setter methods - example

public class Point {

private double x;

private double y;

// constructor methods

public double getX( )

{

return this.x;

}

public double getY( )

{

return this.y;

}

public void setX(double x)

{

this.x=x;

}

public void setY(double y)

{

this.y=y;

} // rest methods

public static void main(String[ ] args)

{

Point p1=new Point(2.0,3.0);

System.out.println(p1.toString());

System.out.print( “Enter the x value “ );

double newX = reader.nextDouble();

p1.setX(newX);

System.out.print( “Enter the y value “ );

double newY = reader.nextDouble();

p1.setY(newY);

System.out.println(p1.toString());

}

This program generates the following output:

x=2.0 y= 3.0

Enter the x value 4.0

Enter the y value 5.0

x=4.0 y= 5.0

27

Page 28: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Class variables - definition

● When a number of objects are created from the same class

definition, they each have their own distinct copies of

instance variables ( תכונות מופע ) .

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

Page 29: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Class variables - implementation public class Point

{

private double x;

private double y;

private static int numPoints = 0;

// constructor

public Point(double x, double y)

{

this.x = x;

this.y = y;

++numPoints;

}

// rest methods

.

.

.

}

Increment numPoints to tell anyone that we have

another instance of this class.

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.

29

Page 30: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Class variables - example

Point

x y

2.0 3.0

p1

Point

x y

4.0 5.0

p2

Point

x y

6.0 7.0

p2 public static void main(String[ ] args)

{

Point p1=new Point(2.0,3.0);

Point p2=new Point(4.0,5.0);

Point p3=new Point(6.0,7.0);

}

numPoints

3

Every instance of the class shares a class variable, which is in one fixed location in memory

30

Page 31: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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 = 3.141592653589793;

▪ Constants defined in this way cannot be reassigned.

▪ By convention, the names of constant values are spelled

in uppercase letters.

31

Page 32: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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

Page 33: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

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 Point.numPoints;

}

// rest methods

.

.

.

}

public static void main(String[] args) { System.out.println("Num of points : "+Point.getNumPoints()); Point p1=new Point(2.0,3.0); System.out.println("Num of points : "+Point.getNumPoints()); Point p2=new Point(3.0,4.0); System.out.println("Num of points : "+Point.getNumPoints()); }

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

Page 34: Object-Oriented Programming Concepts - BGUipc131/wiki.files/Class_Java_7.pdfObject-oriented programming (םימצע החנומ תונכת) involves programming using objects. An object)םצע)represents

Class (static) methods – example 2

public class TestPoint

{

public static int PointsNumber()

{

return Point.getNumPoints();

}

public static void main(String[ ] args)

{

System.out.println("Num of points is: "+PointsNumber());

Point p1=new Point(2.0,3.0);

System.out.println("Num of points is: "+PointsNumber());

Point p2=new Point(3.0,4.0);

System.out.println("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

External method

Main method

34