1 202.1.9031 14.12.14. object-oriented programming ( תכנות מונחה עצמים) involves...

Download 1 202.1.9031 14.12.14. Object-oriented programming ( תכנות מונחה עצמים) involves programming using objects. An object עצם)) represents an entity in the

If you can't read please download the document

Upload: godwin-horatio-stevenson

Post on 18-Jan-2018

227 views

Category:

Documents


0 download

DESCRIPTION

Objects - example 3 Object properties Object behavior

TRANSCRIPT

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 Objects - example 3 Object properties Object behavior Objects - examples Student properties ? Student behavior ? Robot properties ? Robot behavior ? lecturer properties ? lecturer behavior ? 4 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. 5 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. 6 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 namesMethod Names modelstartEngine yearstopEngine Coloraccelerate Classes - examples 7 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. David Ronit Vered Instances of the class Student Ronit 8 Instance of a class - example 9 Instances of a class Point - example 10 ( 0, 0) (2, 3) (-3, 1) (-1.5, -2.5) 4 instances of Point class Class Point 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 11 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. 12 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(); NameTypeMemory Address p1Point3000 p1 x = 0.0 y = 0.0 default values An object reference variable stores the memory address of an object Java 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 - instantiation. For example : Point p2 = new Point(3.5,2,4); Constructors must have the same name as the class itself. NameTypeMemory Address p2Point2000 p2 x = 3.5 y = 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. J AVA 15 Constructors implementation public class Point { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; } // Point 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) 16 Constructor without parameters public Point( ) { this.x = 7.5; this.y = 15.4; } // Point NameTypeMemory Address p3Point1500 p3 x = 7.5 y = 15.4 public Point( ) { } // Point p3 x = 0.0 y = 0.0 Point p3 = new Point( ); Choice 1Choice 2 17 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). 18 Accessing the variables of an object 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 ); If access specifiers of x and y class variables are public,class variables can be initialized by an assignment statement. This would produce following result: p1 = 2.5,-3.9 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( OOP); the object is the focus here, not the method call. We use an object reference to invoke an object's method. file testCircle.java public class Circle { public double x, y; // The coordinates public 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 *this. r); } public double area() { return 3.14 * this.r * this.r; } } // Circle 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 20 Differences between Variables of Primitive Data Types and Object Types 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. 21 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, a data field grades contains a data 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; // students grades array has default value null private char gender; // c has default value '\u0000. } // class Student 22 Class Student methods Copying Variables of Primitive Data Types and Object Types 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. 23 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. 24 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 class Point 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 ); } // main This program generates the following output: x=2.0 y= 3.0 YES file testPoints.javafile Point.java 25 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. 26 Copy constructor 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( ); } // main This program generates the following output: x = 2.0 y = 3.0 p1 xy p1 p2 xy p2 Two different instances of the Point object. 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; } // toString // rest class Point 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); } // main This program generates the following output: x = 2.0 y = 3.0 x = 4.0 y = 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. getter/setter methods - example public class Point { private double x; private double y; // class Point 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 class Point 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()); } // main 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 = Class Rational 31 In mathematics, a rational number is any number that can be expressed as the quotient or fraction a/b of two integers, with the denominator b not equal to zero. The basic arithmetic operations for rational number are addition, subtraction, multiplication, and division. Class Rational represents one rational number with a numerator and denominator. So, a rational number looks like this: numerator denominator In Rational Class we examine the following basic operations: -Equality - Multiplication -Division Class Rational 32 public class Rational { private int x; // numerator private int y; // denominator public Rational (int x, int y) { this.x = x; this.y = y; } // Rational class constructor public int getNumerator() { return this.x; } // getNumerator public int getDenom() { return this.y; { // getDenomirator public void setNumerator( int x) { this.x = x; { // setNumerator public void setDenom( int y) { this.y = y; { // setDenominator Getter methods Setter methods Constructor Class Rational 33 public String toString() { return this.x + "/" + this.y; { // toString public boolean isEqual(Rational num) { return ( (this.x * num.y) == (num.x * this.y) ); { // isEqual public Rational multiply(Rational num) { return new Rational (this.x * num.x, this.y * num.y); { // multiply public Rational divide(Rational num) { if (num.y == 0) return null; return new Rational(this.x * num.y, this.y * num.x)); {// divide toString method These methods return new Rational class variables Class TestRational 34 public class TestRational { public static void main(String[ ] args) { Rational r1 = new Rational (2,3); Rational r2 = new Rational (4,6); System.out.println("r1: + r1); System.out.println("r2: + r2); System.out.println("r1, r2 equal ? + r1.isEqual(r2)); Rational r3 = r1.multiply(r2); System.out.println("r3 = r1*r2: + r3); Rational r4 = r1.divide(r2); System.out.println("r4 = r1/r2: + r4); { // main { // class TestRational This program generates the following output: r1: 2/3 r2: 4/6 r1, r2 equal ? true r3 = r1*r2: 8/18 r4 = r1/r2: 12/12 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. 35 Class variables - implementation public class PointCounter { private double x; private double y; private static int numPoints = 0; public PointCounter(double x, double y) { this.x = x; this.y = y; PointCounter.numPoints++; } // constructor public static int getNumberOfPoints() { return PointCounter.numPoints; } // getNumberOfPoints. } // class PointCounter Increment class variable numPoints to tell anyone that we have another instance of this class. Coordinates - not static, thus not shared among instances of PointCounter. Keeps track of the number of Point objects created. Since it is static, all Point objects share this variable. 36 Rest class PointCounter methods Class variables - implementation, cont. 37 This method returns the new middle point of this point and a given as parameter point p of PointCounter class. public PointCounter middle(PointCounter p) { double middleX = (this.x + p.getX()) / 2; double middleY = (this.y + p.getY()) / 2; return new PointCounter(middleX, middleY); } // middle This method calculates the distance between this point and a given as parameter point p of PointCounter class. public double distance(PointCounter p) } return (Math.sqrt((Math.pow((this.x - p.getX()), 2) + Math.pow((this.y - p.getY()),2)))); } // distance Class variables - creation p1 xy p1 p2 xy p2 p3 xy p3 public static void main(String[ ] args) { PointCounter p1 = new PointCounter(2.0,3.0); PointCounter p2 = new PointCounter(4.0,5.0); PointCounter p3 = new PointCounter(6.0,7.0); } // main numPoints 3 Every instance of the class PointCounter shares a class variable, which is in one fixed location in memory. 38 Class TestPointCounter 39 public class TestPointCounter { public static void main(String[ ] args) } PointCounter point1 = new PointCounter(9,9); PointCounter point2 = new PointCounter(5,5); double dis = point1.distance(point2); System.out.println("The distance between the points is :" + dis); PointCounter point3 = point1.middle(point2); System.out.println("The middle point is : " + point3); System.out.println("Number of points is : " + PointCounter.getNumberOfPoints()); } // main } // TestPointCounter This program generates the following output: The distance between the points is : 5.65 The middle point is : 7.0,7.0 Number of points is : 3 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 = ; Constants defined in this way cannot be reassigned. By convention, the names of constant values are spelled in uppercase letters. 40 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 PointCounter class to access the numPoints static field : Class (static) methods example 1 public class PointCounter { private double x; private double y; private static int numPoints = 0; // constructors public static int getNumPoints( ) { return PointCounter.numPoints; } // rest class PointCounter methods. } // class PointCounter public static void main(String[ ] args) { System.out.println("Num of points : + PointCounter.getNumPoints()); PointCounter p1 = new PointCounter(2.0,3.0); System.out.println("Num of points : + PointCounter.getNumPoints()); PointCounter p2 = new PointCounter(3.0,4.0); System.out.println("Num of points : + PointCounter.getNumPoints()); } // main 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. 42 Class (static) methods example 2 public class TestPointCounter { public static int PointsNumber() { return PointCounter.getNumPoints(); } // PointsNumber public static void main(String[ ] args) { System.out.println("Num of points is: + PointsNumber()); PointCounter p1= new PointCounter(2.0,3.0); System.out.println("Num of points is: + PointsNumber()); PointCounter p2 = new PointCounter(3.0,4.0); System.out.println("Num of points is: + PointsNumber()); } // main } // class TestPoint This program generates the following output: Num of points is: 0 Num of points is: 1 Num of points is: 2 External (static) method Main method 43