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

Slides:



Advertisements
Similar presentations
Based on Java Software Development, 5th Ed. By Lewis &Loftus
Advertisements

© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Fields, Constructors, Methods
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
Java is an Object-Oriented Language b In structured programming languages, methods define the structure of the programs, they are basic building blocks.
ECE122 L6: Problem Definition and Implementation February 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 6 Problem Definition and Implementation.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Classes, Encapsulation, Methods and Constructors
Aalborg Media Lab 26-Jun-15 Software Design Lecture 5 “ Writing Classes”
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Writing Classes (Chapter 4)
Java Coding 5 David Davenport Computer Eng. Dept., Bilkent University Ankara - Turkey. To object or not…
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 4 -2 part Writing Classes 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Procedural programming in Java Methods, parameters and return values.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
© 2004 Pearson Addison-Wesley. All rights reserved September 12, 2007 Encapsulation ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
CSE 1201 Object Oriented Programming Introduction.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Anatomy of a Class & Method
Classes A class is a blueprint of an object
Chapter 4: Writing Classes
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Encapsulation & Visibility Modifiers
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Chapter 4: Writing classes
Outline Writing Classes Copyright © 2012 Pearson Education, Inc.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Anatomy of a Method.
Chapter 4 Writing Classes.
Outline Anatomy of a Class Encapsulation Anatomy of a Method
CSE 1201 Object Oriented Programming
Defining Classes and Methods
Presentation transcript:

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

2 Objects everywhere... Real world entities

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 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 Objects have identity... Merhaba ben Ayse My book Dombo the elephant Our house The neighbour’s cat Hasan’s computer

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

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

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

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 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 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 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 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 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 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 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 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 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 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 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 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 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 Pisti