Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

Slides:



Advertisements
Similar presentations
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Advertisements

CSCI 1100/ , 6.2, 6.4 April 12, 15, 17.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Lecture 2 Basics of C#. Members of a Class A field is a variable of any type that is declared directly in a class. Fields are members of their containing.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Road Map Introduction to object oriented programming. Classes
Chapter 3, More on Classes & Methods Clark Savage Turner, J.D., Ph.D. Copyright 2003 CSTurner, from notes and text.
Enhancing classes Visibility modifiers and encapsulation revisited
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Introduction to methods Chapter 5: Classes and Objects in Depth.
Reference … and Misc Other Topics Clark Savage Turner, J.D., Ph.D. Some lecture slides have been adapted from those developed.
1 Memory Model of A Program, Methods Overview l Memory storage areas for an executing program l Introduction to methods and methods definitions l General.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
1 Lecture 4 Objects and Classes Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung Institute of Technology.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Writing Classes (Chapter 4)
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Classes CS 21a: Introduction to Computing I First Semester,
Chapter 7 Objects and Classes 1 Fall 2012 CS2302: Programming Principles.
ACO 101: Introduction to Computer Science Anatomy Part 2: Methods.
Learners Support Publications Classes and Objects.
Java Software Solutions Lewis and Loftus Chapter 4 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects and Classes -- Introduction.
Chapter 4 Writing Classes Part 2. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Classes A class can contain data declarations and method declarations.
Week 4 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Chapter 4 Introduction to Classes, Objects, Methods and strings
CSE 501N Fall ‘09 04: Introduction to Objects 08 September 2009 Nick Leidenfrost.
© 2004 Pearson Addison-Wesley. All rights reserved September 14, 2007 Anatomy of a Method ComS 207: Programming I (in Java) Iowa State University, FALL.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
C# Programming Methods.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
CS 100Lecture71 CS100J Lecture 7 n Previous Lecture –Computation and computational power –Abstraction –Classes, Objects, and Methods –References and aliases.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 3 Implementing Classes
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
Lecture 3 John Woodward.
Lesson C – Classes & Objects
Java Primer 1: Types, Classes and Operators
Implementing Classes Yonglei Tao.
Chapter 4: Writing Classes
Object-Oriented Programming: Classes and Objects
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.
More Object Oriented Programming
Chapter Three - Implementing Classes
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
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Object Oriented Programming
Classes and Objects.
Object Oriented Programming Review
Submitted By : Veenu Saini Lecturer (IT)
Classes CS 21a: Introduction to Computing I
Corresponds with Chapter 5
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation revisited basic programming concepts object oriented programming topics in computer science syllabus

unit 4II 2 Objects and Pointers to objects H A class defines the characteristics associated with an object; when an object is created, it is allocated a block of memory sufficient to hold all its state variables H Variables of type object reference hold the memory address of the actual location of the data ChessPiece bishop1; bishop1 = new ChessPiece(“bishop”,”b”,1); H The object reference variable and the object itself are separate entities; why? when a variable of type object is defined, the size of the memory block it will require is not known; on the other hand, a pointer is a primitive type we can treat all object references the same way bishop1

unit 4II 3 Designing a class: the class abstraction // A clock representation class: clock instances // represent a point of time during the day public class Clock { // The hours, minutes, and second read private int hours, minutes, seconds; //... } Clock(int hours, int minutes, int seconds) int getSeconds() void secondElapsed() int getMinutes() int getHours()...

unit 4II 4 Method Declarations Revisited H A method declaration begins with a method header String seeTime (int hours, int minutes, int seconds) methodname returntype parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal argument

unit 4II 5 Method Declarations H The method header is followed by the method body String seeTime (int hours, int minutes, int seconds) { String result = hours + `:` + minutes + `:` + seconds; return result; } The return expression must be consistent with the return type result is local data It is created each time the method is called, and is destroyed when it finishes executing

unit 4II 6 Constructors H Objects must be initialized before they can be used: We must specify the initial state of the object before we can use it This is very similar to primitive data types: when we declare a new variable of type int, for example, we must give it an initial value H We specify the way an object is initialized using a constructor, which is a special method invoked every time we create a new object

unit 4II 7 Constructors // A clock representation class; clock instances // represent a point of time during the day public class Clock { // The hours, minutes, and second read private int hours, minutes, seconds; // Constructs a new clock, sets the // clock to the time 00:00:00 public Clock() { hours = 0; minutes = 0; seconds = 0; } }

unit 4II 8 Constructors H The statement new Clock() does the following :

unit 4II 9 Constructors H The statement new Clock() does the following : 1) Allocates the memory for a new clock object clock hours minutes seconds

unit 4II 10 clock hours 0 minutes 0 seconds 0 Constructors H The statement new Clock() does the following : 1) Allocates the memory for a new clock object 2) Initializes its state by calling the constructor

unit 4II 11 Constructors Revisited H 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 H The programmer does not have to define a constructor for a class

unit 4II 12 Methods H To make the clock object useful, we must provide methods that define its behavior H Example: // Advance the clock by one hour public void hourElapsed() { hours = (hours + 1) % 24; } // Return the hour read public int getHours() { return hours; }

unit 4II 13 Modifiers of methods  The modifier public denotes that the methods hourElapsed() and getHour() are part of the interface of the class (the services that the class exposes to outside world clients)  The keyword void denotes that the method hourElapsed() has no return value

unit 4II 14 Return Types H The return type of a method indicates the type of value that the method sends back to the calling client  The return-type of getHours() is int ; when a client asks for the hours read of a clock it gets the answer as an int value  A method that does not return a value (such as hourElapsed() ) has a void return type  The return statement specifies the value that should be returned, which must conform with the return type of the method

unit 4II 15 Method Context  The getHours() and hourElapsed() methods are instance methods, which means they act on a particular instance of the class H They cannot be invoked “out of the blue”, but must act on a particular object: Clock c = new Clock(); getHours(); // error: of which clock? c.getHours(); // will return 0 H An instance method is executed in the context of the object it acts upon

16 unit 6 public class ClockTest { public static void main(String[] args) { Clock swatch = new Clock(); Clock seiko = new Clock(); System.out.println(swatch.getHours()); // 0 System.out.println(seiko.getHours()); // 0 swatch.hourElapsed(); System.out.println(swatch.getHours()); // 1 System.out.println(seiko.getHours()); // 0 } }

unit 4II 17 The this Reference  When appearing inside an instance method, the this keyword denotes a reference to the object that the method is acting upon H The following are equivalent: public int getHours() { return hours; } public int getHours() { return this.hours; }

unit 4II 18 Method Parameters H A method can be defined to accept zero or more parameters; each parameter in the parameter list is defined by its type and name H The parameters in the method definition are called formal parameters; the values passed to a method when it is invoked are called actual parameters H The name of the method together with the list of its formal parameters is called the signature of the method public void setTime(int hours, int minutes, int seconds)

19 unit 6 public class Clock { private int hours, minutes, seconds; // Sets the clock to the specified time. // If one of the parameters is not in the allowed // range, the call does not have any effect on the clock. hours: the hours to be set (0-23) minutes: the minutes to be set (0-59) seconds: the seconds to be set (0-59) public void setTime(int hours, int minutes, int seconds) { if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60) && (hours >= 0) && (hours < 24)) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } // no effect if input is illegal } }

unit 4II 20 public class student { private long ID; private String maslul; // Constructor public student(long ID, String maslul) { this.ID =ID; this.maslul = maslul; } // method: change maslul public void changeMaslul(String maslul) { this.maslul = maslul; } } Example: a Student Object Student Rachel; Rachel = new Student( , “math”); Rachel.changeMaslul(“computer science”);

unit 4II 21 Passing parameters H Each time a method is called, the actual arguments in the invocation are copied into the formal arguments String seeTime (int hours, int minutes, int seconds) { String result = hours + `:` + minutes + `:` + seconds; return result; } time = obj.seeTime (20, 30, 40); return 20:30:40

unit 4II 22 Example: a Bank Account Object BankAccount public BankAccount(long accountNumber, String owner) public void deposit(float amount) public void withdraw(float amount) public void transfer (float amount, BankAccount targetAccount)

unit 4II 23 Writing Classes H An aggregate object is an object that contains references to other objects  A BankAccount object is an aggregate object because it contains a reference to a String object (that holds the owner's name) H An aggregate object represents a has-a relationship H A bank account has a owner

24 unit 6 // A bank account public class BankAccount { private long accountNumber; private float balance; // The balance in dollars private String owner; // Constructs a new empty account public BankAccount(long accountNumber, String name) { this.accountNumber = accountNumber; this.owner = name; this.balance = 0; } // Deposites a given amount into the account public void deposit(float amount) { //... perhaps perform some security checks balance = balance + amount; }

25 unit 6 // Withdraws a given amount from the account public void withdraw(float amount) { //... perhaps perform some security checks balance = balance - amount; } // Transfers a given amount into another bank account public void transfer(float amount, BankAccount targetAcc) { //... perhaps perform some security checks this.withdraw(amount); targetAcc.deposit(amount); } BankAccount tomAccount = new BankAccount( ,”Tom”); BankAccount shirAccount = new BankAccount( ,”Shir”); tomAccount.deposit(500); // Tom’s balance = 500 tomAccount.transfer(700,shirAccount); // Tom’s balance = -200, Shir’s balance = 700

unit 4II 26 Encapsulation not Among Instances of Same Class H Sometimes object instances of the same class need to access each other’s “guts” (e.g., for state copying - if we want to create an identical instance of an object we have)  Example: from within a BankAccount object, any private member of a different BankAccount object can be accessed public void transfer(float amount, BankAccount targetAcc) { //... perhaps perform some security checks this.withdraw(amount); targetAcc.balance += amount; // not: targetAcc.deposit(amount) }

unit 4II 27 Passing Objects to Methods H Parameters in a Java method are passed by value: a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header) Passing parameters is essentially an assignment H Both primitive types and object references can be passed as parameters H When an object is passed to a method, the actual parameter and the formal parameter become aliases