Download presentation
Presentation is loading. Please wait.
1
Object Oriented Programming
2
OOP The fundamental idea behind object-oriented programming is:
The real world consists of objects. Computer programs may contain computer world representations of the things (objects) that constitute the solutions of real world problems. Real world objects have two parts: Properties (or state :characteristics that can change), Behavior (or abilities :things they can do). To solve a programming problem in an object-oriented language, the programmer no longer asks how the problem will be divided into functions, but how it will be divided into objects. The emphasis is on data
3
Kinds of Objects Human Entities: employee, customer, worker, manager…
Graphics program: point, line, circle… Data storage: linked list, stack, matrix… Car, Robot …
4
Classes and objects class: A program entity that represents either:
1. A program / module, or 2. A template for a new type of objects. The Robot class is a template for creating Robot objects. object: An entity that belongs to the corresponding class. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects.
5
What is a class? Essentially a struct with built-in functions
class Circle { double radius = 0.0; double Area() double pi = ; return (pi * radius * radius); } 5
6
A swap method? Does the following swap method work? Why or why not?
public static void main(String[] args) { int a = 7; int b = 35; // swap a with b? swap(a, b); System.out.println(a + " " + b); } public static void swap(int a, int b) { int temp = a; a = b; b = temp; It's basically not possible to write a swap method that accepts two ints. swap can't escape from itself to modify the outside world.
7
Value semantics value semantics: Behavior where values are copied when assigned, passed as parameters, or returned. Primitive types use value semantics. When one variable is assigned to another, its value is copied. Modifying the value of one variable does not affect others. int x = 5; int y = x; // x = 5, y = 5 y = 17; // x = 5, y = 17 x = 8; // x = 8, y = 17
8
Reference semantics (objects)
reference semantics: Behavior where variables actually store the address of an object in memory. When one variable is assigned to another, the object is not copied; both variables refer to the same object. Modifying the value of one variable will affect others. int[] a1 = {4, 15, 8}; int[] a2 = a1; // refer to same array as a1 a2[0] = 7; System.out.println(a1[0]); // 7 index 1 2 value 7 15 8 index 1 2 value 4 15 8 a1 a2
9
References and objects
Arrays and objects use reference semantics. Why? efficiency. Copying large objects slows down a program. sharing. It's useful to share an object's data among methods. When an object is passed as a parameter, the object is not copied. The parameter refers to the same object. If the parameter is modified, it will affect the original object This is called shallow copy Deep Copy The object is copied, became two independent objects a copy is made not only of the top-level object, but of all the objects referenced by the original object.
10
Objects object: An entity that encapsulates data and behavior.
data: variables inside the object behavior: methods inside the object You interact with the methods; the data is hidden in the object. Constructing (creating) an object: Type objectName = new Type(parameters); Calling an object's method: objectName.methodName(parameters);
11
Classes class: A program entity that represents either:
1. A program / module, or 2. A template for a new type of objects. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects. abstraction: Separation between concepts and details. Objects and classes provide abstraction in programming. Treat objects as black boxes – deal only with the interface
12
Blackbox analogy creates iPod blueprint
state: current song volume battery life behavior: power on/off change station/song change volume choose random song creates iPod #1 state: song = "1,000,000 Miles" volume = 17 battery life = 2.5 hrs behavior: power on/off change station/song change volume choose random song iPod #2 state: song = "Letting You" volume = 9 battery life = 3.41 hrs iPod #3 state: song = "Discipline" volume = 24 battery life = 1.8 hrs
13
Encapsulation By default the class definition encapsulates, or hides, the data inside it. Key concept of object oriented programming. The outside world can see and use the data only by calling the build-in functions. Called “methods” 13
14
Encapsulation To create software models of real world objects both data and the functions that operate on that data are combined into a single program entity. Data represent the properties (state), Functions represent the behavior of an object. Data and its functions are said to be encapsulated into a single entity. An object’s functions, called member functions typically provide the only way to access its data. The data is hidden, so it is safe from accidental alteration. This simplifies writing, debugging, and maintaining the program.
15
Encapsulation encapsulation: Hiding implementation details from clients. Encapsulation enforces abstraction. separates external view (behavior) from internal view (state) protects the integrity of an object's data
16
Class Members Methods and variables declared inside a class are called members of that class. Member variables are called fields. Member functions are called methods. In order to be visible outside the class definition, a member must be declared public. As written in the previous example, neither the variable radius nor the method Area could be seen outside the class definition. 16
17
Making a Method Visible
To make the Area() method visible outside we would write it as: public double Area() { return pi * radius * radius; } We will keep the radius and pi field private. 17
18
Interface vs. Implementation
The public definitions form the interface for the class A contract between the creator of the class and the users of the class. Should never change. Implementation is private Users cannot see. Users cannot have dependencies. Can be changed without affecting users. 18
19
Our task In the following slides, we will implement a Point class as a way of learning about defining classes. We will define a type of objects named Point. Each Point object will contain x/y data called fields. Each Point object will contain behavior called methods. Client programs will use the Point objects.
20
Point objects (desired)
Point p1 = new Point(5, -2); Point p2 = new Point(); // origin, (0, 0) Data in each Point object: Methods in each Point object: Field name Description x the point's x-coordinate y the point's y-coordinate Method name Description setLocation(x, y) sets the point's x and y to the given values translate(dx, dy) adjusts the point's x and y by the given amounts distance(p) how far away the point is from point p
21
Point class, version 1 The above code creates a new type named Point.
public class Point { int x; int y; } Save this code into a file named Point.java. The above code creates a new type named Point. Each Point object contains two pieces of data: an int named x, and an int named y. Point objects do not contain any behavior (yet).
22
Accessing fields Other classes can access/modify an object's fields.
access: variable.field modify: variable.field = value; Example: Point p1 = new Point(); Point p2 = new Point(); System.out.println("the x-coord is " + p1.x); // access p2.y = 13; // modify
23
A class and its client Point.java is not, by itself, a runnable program. A class can be used by client programs. Point.java (class of objects) public class Point { int x; int y; } PointMain.java (client program) public class PointMain { main(String args) { Point p1 = new Point(); p1.x = 7; p1.y = 2; Point p2 = new Point(); p2.x = 4; p2.y = 3; ... } x 7 y 2 x 4 y 3
24
Instance methods instance method (or object method): Exists inside each object of a class and gives behavior to each object. public type name(parameters) { statements; } Mutator methods Change field values Access methods Returns a result without any change
25
Mutator method answers
public void setLocation(int newX, int newY) { x = newX; y = newY; } public void translate(int dx, int dy) { x = x + dx; y = y + dy; // alternative solution that utilizes setLocation setLocation(x + dx, y + dy);
26
Accessor method questions
Write a method distance that computes the distance between a Point and another Point parameter. Use the formula: Write a method distanceFromOrigin that returns the distance between a Point and the origin, (0, 0).
27
Accessor method answers
public double distance(Point other) { int dx = x - other.x; int dy = y - other.y; return Math.sqrt(dx * dx + dy * dy); } public double distanceFromOrigin() { return Math.sqrt(x * x + y * y);
28
tells Java how to convert an object into a String
The toString method tells Java how to convert an object into a String Point p1 = new Point(7, 2); System.out.println("p1: " + p1); // the above code is really calling the following: System.out.println("p1: " + p1.toString()); Every class has a toString, even if it isn't in your code. Default: class's object's memory address (base 16)
29
toString syntax public String toString() {
code that returns a String representing this object; } Method name, return, and parameters must match exactly. Example: // Returns a String representing this Point. return "(" + x + ", " + y + ")";
30
Constructors constructor: Initializes the state of new objects.
public type(parameters) { statements; } runs when the client uses the new keyword no return type is specified; it implicitly "returns" the new object being created If a class has no constructor, Java gives it a default constructor with no parameters that sets all fields to 0.
31
Constructor example public class Point { int x; int y;
// Constructs a Point at the given x/y location. public Point(int initialX, int initialY) { x = initialX; y = initialY; } ...
32
Multiple constructors
A class can have multiple constructors. Each one must accept a unique set of parameters. Exercise: Write a Point constructor with no parameters that initializes the point to (0, 0). // Constructs a new point at (0, 0). public Point() { x = 0; y = 0; }
33
Common constructor bugs
1. Re-declaring fields as local variables ("shadowing"): public Point(int initialX, int initialY) { int x = initialX; int y = initialY; } This declares local variables with the same name as the fields, rather than storing values into the fields. The fields remain 0. 2. Accidentally giving the constructor a return type: public void Point(int initialX, int initialY) { x = initialX; y = initialY; This is actually not a constructor, but a method named Point
34
A field that cannot be accessed from outside the class
Private fields A field that cannot be accessed from outside the class private type name; Examples: private int id; private String name; Client code won't compile if it accesses private fields: PointMain.java:11: x has private access in Point System.out.println(p1.x); ^
35
Accessing private state
// A "read-only" access to the x field ("accessor") public int getX() { return x; } // Allows clients to change the x field ("mutator") public void setX(int newX) { x = newX; Client code will look more like this: System.out.println(p1.getX()); p1.setX(14);
36
The this keyword this : Refers to the implicit parameter inside your class. (a variable that stores the object on which a method is called) Refer to a field: this.field Call a method: this.method(parameters); One constructor this(parameters); can call another:
37
Fixing shadowing Inside setLocation, public class Point {
private int x; private int y; ... public void setLocation(int x, int y) { this.x = x; this.y = y; } Inside setLocation, To refer to the data field x, say this.x To refer to the parameter x, say x
38
Calling another constructor
public class Point { private int x; private int y; public Point() { this(0, 0); // calls (x, y) constructor } public Point(int x, int y) { this.x = x; this.y = y; ... Avoids redundancy between constructors Only a constructor (not a method) can call another constructor
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.