Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation."— Presentation transcript:

1 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

2 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

3 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()...

4 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

5 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

6 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

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

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

9 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

10 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

11 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

12 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; }

13 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

14 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

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

17 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; }

18 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 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. // @param hours: the hours to be set (0-23) // @param minutes: the minutes to be set (0-59) // @param 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 } }

20 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(123456789, “math”); Rachel.changeMaslul(“computer science”);

21 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

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

23 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 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 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(1398723,”Tom”); BankAccount shirAccount = new BankAccount(1978394,”Shir”); tomAccount.deposit(500); // Tom’s balance = 500 tomAccount.transfer(700,shirAccount); // Tom’s balance = -200, Shir’s balance = 700

26 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) }

27 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


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

Similar presentations


Ads by Google