Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 OOP  Software usually tries to model real world problems  What does the world look like?

Similar presentations


Presentation on theme: "1 OOP  Software usually tries to model real world problems  What does the world look like?"— Presentation transcript:

1 1 OOP  Software usually tries to model real world problems  What does the world look like?

2 2 Objects everywhere... Real world entities

3 3 World  The world is a set of things interacting with each other.  OOP is more natural to humans, but less natural to computers  Computers (usually) have a single thread of control, so objects take turns

4 4 Describing the world  Describe a particular person Ayse has long blond hair, green eyes, is 1.63m tall, weighs 56Kg and studies computer engineering. Now lying down asleep. Mehmet studies electronics, has short black hair and brown eyes. He is 180cm and 75 kilos. Now running to class!  Notice how all have specific values of name, height, weight, eye colour, state, …

5 5 Objects have identity... Merhaba ben Ayse My book Dombo the elephant Our house The neighbour’s cat Hasan’s computer

6 6 Objects have state... Red Lying Happy Hooked ill Broken

7 7 Objects have behavior…. Hello, I am John Nice to meet you da da … Grrrrrrrr Vroemm

8 8 Java OOP terminology  Class - Category Properties/states Functionality/Services (examines/alters state) data methods object - Individual/unique thing (an instance of a class) Particular value for each property/state & functionality of all members of class.

9 9 Java OOP Software  Software System Set of objects Which interact with each other One object will send a message to another object asking it to do a particular task. The first object does not need to know how the task is done (only how to request that it be done.) This corresponds to calling one of the second object’s methods! Created (instantiated) from class definitions Person AyseDavid “David” David: Say your name

10 10 In more detail  Create & manipulate person objects Name: “Ayse” Age: 18 Salary: 500 Comments: “Good student” Name: “David” Age: 22 Salary: 2000 Comments: “Teaches CS101” Person name, age, salary, comments sayName, getNetSalary getComments setComments increaseAge …

11 11 Coding Java Classes // header public class Person { // properties // constructors // methods } public void sayName() { System.out.println( name); } Stringname; intage; doublesalary; Stringcomments; public Person( StringtheName, inttheAge ) { name = theName; age = theAge; comments = “”; }

12 12 Creating & Using Objects  Always Declare variable to “hold” object Create object using “new” statement Call object’s methods “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} Person aStudent; aStudent = new Person( “Ayse”, 18); aStudent.sayName(); Put this in method of another class, (e.g main method)

13 13 Creating & Using Objects Person aStudent; aStudent = new Person( “Ayse”, 18); Person friend; friend = new Person( “David”, 22); “Ayse” name: 18 age: 0.0 salary: “” comments: aStudent {Person} “David”name: 22age: 0.0 salary: “” comments: friend {Person} friend.increaseAge(); aStudent.setComments( “Good student”); 23 “Good student”

14 14 Data Scope  The scope of data is the area in a program in which that data can be used (referenced)  Data declared at the class level can be used by all methods in that class  Data declared within a method can only be used in that method  Data declared within a method is called local data  Data and methods are primary components of a class, they work together to bring the concept alive as a unit

15 15 Local and Class scope public class X{ private int a; // a has class scope, can be seen from // anywhere inside the class …. public void m() { a=5; // no problem int b = 0; // b is declared inside the method, local scope ….. } // here variable b is destroyed, no one will remember him public void m2() { a=3; // ok b = 4; // who is b? compiler will issue an error }

16 16 Hotel room example public class X { int a; int b; void m1 () { System.out.println(a); m2(); } void m2() { System.out.println(b); } a=3 b=4 o1 a=1 b=2 o2

17 17 Parameters  Each time a method is called, the actual arguments in the invocation are copied into the formal arguments char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc (25, count, "Hello");

18 18 Parameters …  We can view the parameters as local variables given initial values when the method gets called. Therefore they have local scope, valid only inside the method char calc () { int num1 = 25; int num2 = count; String message = “Hello”; int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc (25, count, "Hello");

19 19 Constructors Revisited  Recall that a constructor is a special method that is used to set up a newly created object  When writing a constructor, remember that: it has the same name as the class it does not return a value it has no return type, not even void it often sets the initial values of instance variables  The programmer does not have to define a constructor for a class

20 20 Writing Classes  Sometimes an object has to interact with other objects of the same type  For example, we might add two Rational number objects together as follows: r3 = r1.add(r2);  One object ( r1 ) is executing the method and another ( r2 ) is passed as a parameter  See RationalNumbers.java (page 196)RationalNumbers.java  See Rational.java (page 197)Rational.java

21 21 QuadraticPolynomial.java public class QuadraticPolynomial { //instance variables private double a; private double b; private double c; // constructor public QuadraticPolynomial(double _a, double _b, double _c) { a = _a; b = _b; c = _c; } //getter (Accessor) methods public double getA() { return a ; } …

22 22 public double evaluate(double x) { return a * x * x + b * x + c; } public QuadraticPolynomial add(QuadraticPolynomial other) { return new QuadraticPolynomial(a + other.getA(), b + other.getB(), c + other.getC() ); } // creates and returns a new polynomial which is is the derivative // of this polynomial public QuadraticPolynomial derivative() { return new QuadraticPolynomial(0, 2 * a, b); }

23 23 public boolean equals(QuadraticPolynomial other) { return (a == other.getA() && b == other.getB() && c == other.getC()); } public double minValue(double start, double end, double delta){ double minValue = evaluate(start); double x = start + delta; while ( x <= end ) { double currValue = evaluate(x); if (currValue < minValue) minValue = currValue; x += delta; } return minValue; }

24 24 QuadraticPolynomial qp1 = new QuadraticPolynomial(-1, -6, -5); QuadraticPolynomial qp2 = new QuadraticPolynomial(2, 2, 13); QuadraticPolynomial sum = qp1.add(qp2); double minValue = sum.minValue(-4, 4, 0.05); System.out.println("The experimental minimum value is " + minValue); QuadraticPolynomial sumd = sum.derivative(); //find the value of x where the derivative equals to 0 double extremePoint = -1 * sumd.getC() / sumd.getB(); QuadraticPolynomial sumdd = sumd.derivative(); if ( sumdd.evaluate(extremePoint) <= 0) System.out.println("No minimum value"); else System.out.println("The minimum value is " + sum.evaluate(extremePoint) );

25 25

26 26 Card1 code Card1 code public class Card1 { //constants for face values private static int ACE = 0; private static int JACK = 10; private static int QUEEN = 11; private static int KING = 12; private static String ACE_ST = "Ace"; private static String JACK_ST = "Jack"; private static String QUEEN_ST = "Queen"; private static String KING_ST = "King"; // constants for suit values private static int CLUBS = 0;...... private static String CLUBS_ST = "Clubs";...

27 27 private int face; private int suit; // creates a random card public Card1 () { face = (int) (Math.random () * 13); suit = (int) (Math.random () * 4); } public boolean isJack() { return face == JACK; } public boolean equals(Card1 other) { return face == other.face && suit == other.suit; } public boolean sameFace(Card1 other) { return face == other.face; }

28 28 public int getScore() { return 1; // ?????????????????????????????????????? } public String toString() { return getFaceName() + " of " + getSuitName(); } private String getFaceName() { if (face == ACE) return ACE_ST; else if... // must be something between 2 and 10 return "" + (face + 1) ; // Integer.toString(face) } private String getSuitName() {... }

29 29 Abstraction  An abstraction hides (or ignores) unnecessary details, denotes the essential properties of an object  Objects are abstractions of real world entities Abstraction A car consists of four wheels an engine, accumulator and brakes.

30 30 Card Abstraction  A real world playing card has lots of properties like size, weight, color, texture, …  For our purposes, we decided which properties/behavior we really care about to play pisti, and ignored the rest

31 31 Multiple Abstractions A single thing can have multiple abstractions Example: a protein is…  a sequence of amino acids  a complicated 3D shape (a fold)  a surface with “pockets” for ligands

32 32 Choosing Abstractions Abstractions can be about  tangible things (a vehicle, a car, a map) or  intangible things (a meeting, a route, a schedule) An example:  Abstraction name: light  Light’s wattage (i.e.,energy usage)  Light can be on or off  There are other possible properties (shape, color, socket size, etc.), but we have decided those are less essential  The essential properties are determined by the problem

33 33 Modeling Abstraction using Classes A class defines  all attributes/properties  all behaviors/operations of an abstraction In Java…  Attributes/properties correspond to fields (or variables)  Behaviors/operations correspond to methods class light { // Instance variables private int wattage; private boolean on; // Instance methods public void switchOn ( ) { on = true; } public void switchOff ( ) { on = false; } public boolean isOn ( ) { return on; } public int getWattage ( ) { return wattage; } }

34 34 Encapsulation  Encapsulation (information hiding) No direct access to the parts of an object No dependence on the object’s implementation Classes support a particular kind of abstraction, encouraging separation between an object’s operations and the implementations of those operations  This allows and encourages encapsulation  Objects are regarded as “black boxes” whose internals are hidden  Separation of contract (i.e., what operations are available) and implementation

35 35 Contract vs. Implementation  A class can be viewed as a contract; the contract specifies what operations are offered by the class In Java, this corresponds to the method headings for the methods that are public  A class can be viewed as an implementation; the implementation specifies how the desired behavior is produced In Java, this corresponds to the method-bodies and the (nonpublic) instance variables

36 36 Programming Implications  Encapsulation makes programming easier As long as the contract is the same, the client doesn’t care about the implementation  In Java, as long as the method signatures are the same, the implementation details can be changed In other words, I can write my program using simple implementations; then, if necessary, I can replace some of the simple implementations with efficient implementations

37 37 Encapsulation  An object should be self-governing  Any changes to the object's state (its variables) should be made only by that object's methods  We should make it difficult, if not impossible, to access an object’s variables other than via its methods  The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished

38 38 Encapsulation  An encapsulated object can be thought of as a black box  Its inner workings are hidden to the client, which invokes only the interface methods Client Methods Data

39 39 Another Card Implementation Another Card Implementation private String face; private String suit; // creates a random card public Card2 () { int faceCode = (int) (Math.random () * 13); face = getFaceName(faceCode); int suitCode = (int) (Math.random () * 4); suit = getSuitName(suitCode); } public boolean isJack() { return face.equals(JACK_ST); } public boolean equals(Card2 other) { return face.equals (other.face) && suit.equals ( other.suit); } public boolean sameFace(Card2 other) { return face.equals(other.face); }.. …

40 40 Pisti


Download ppt "1 OOP  Software usually tries to model real world problems  What does the world look like?"

Similar presentations


Ads by Google