Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Classes and Objects

Similar presentations


Presentation on theme: "Introduction to Classes and Objects"— Presentation transcript:

1 Introduction to Classes and Objects
1 Introduction to Classes and Objects

2 OBJECTIVES In this chapter you will learn:
What classes, objects, methods and instance variables are. How to declare a class and use it to create an object. How to declare methods in a class to implement the class’s behaviors. How to declare instance variables in a class to implement the class’s attributes. How to call an object’s method to make that method perform its task. The differences between instance variables of a class and local variables of a method. How to use a constructor to ensure that an object’s data is initialized when the object is created. The differences between primitive and reference types.

3 1.1 Introduction 1.2 Classes, Objects, Methods and Instance Variables 1.3 Declaring a Class without/with a Method and Instantiating an Object of a Class 1.4 Declaring a Method without/with a Parameter 1.5 Instance Variables, set Methods and get Methods 1.6 Primitive Types vs. Reference Types 1.7 Initializing Objects with Constructors

4 Classes Classes are constructs that define objects of the same type.
A Java class uses variables to define data fields and methods to define behaviors. Additionally, a class provides a special type of methods, known as constructors, which are invoked to construct objects from the class.

5 Classes and Objects An object has both a state and behavior. The state defines the object, and the behavior defines what the object does.

6 1.2 Classes, Objects, Methods and Instance Variables (Cont.)
Classes contain one or more attributes Specified by instance variables Carried with the object as it is used

7 1.2 Classes, Objects, Methods and Instance Variables
Class provides one or more methods Method represents task in a program Describes the mechanisms that actually perform its tasks Hides from its user the complex tasks that it performs Method call tells method to perform its task

8 a generic class { // body of a method statement(s);
class class_name { access_modifier type instance_variable_name = initial_value; access_modifier type instance_variable_name; // methods access_modifier return_type method_name(parameter_list) { // body of a method statement(s); return return_expression; } // end of method .. } // end of class

9 Examples of Classes and Objects
In registration system classes: Student, Instructor, Adivisor, Course Student: blueprint for a typical student chacteristics – atributes – instance variables name, last name, address, deparment, advisor.,,, courses taken behavior – by methods add course, delete course, send approvel, concent request what about gpa? bevaior or chacteristic

10 Examples of Classes and Objects (cont.)
Intructor: charecteristics: name, department, title, behavior: approve/reject programs, approve/reject concents give courses, see course lists Course charcateristics: name, credit, desription, prerequizite(s), hours How can a course behave?

11 Objects Specific sturdents are instances of the Student class
they are Studnet objects each Student object has a different name, address, department,... The Student class indicats what characteristics a particular student should have Each shoud have a name, ad department and what can a student do – hew it behave in the program

12 Objects (cont.) Similarly there are instances of Instructors, Courses
Every course opended is an instance of the Course class it has a name, credit, hours and so on. Instructor class indicates the charcateristics and behavior of a typical insturtor in the registration system. Each particular instructor has a specific value for these characteristics and behave as indicated by methods of the Instructor class.

13 Another Example Geometric program – a game program
Classes: regrangle, circle, square, cube,... Rectangle charceteristics: heigth, width, position, color behavior: move, expend or shrink what about area characteristics or behavior? area can be calculated from heitht nnd width knowing heigth and width of a rectangle – their values can change through out the program execution any call to the area method returns a value to area

14 Reference and primitive types
build in types– primitive types byte,short,int,long,float,double,char,boolean single variables – value of a singel varible initial default values are 0 for boolean falce for local variables initial default is not defined Referece types: holds the address of an object in the memory

15 Primitive Types vs. Reference Types
Types in Java Primitive boolean, byte, char, short, int, long, float, double Reference (sometimes called nonprimitive types) Refers to objects Default value of null Used to invoke an object’s methods

16 Software Engineering Observation 3.4
A variable’s declared type (e.g., int, double or GradeBook) indicates whether the variable is of a primitive or a reference type. If a variable’s type is not one of the eight primitive types, then it is a reference type. For example, Rectangel r1 indicates that r1 is a reference to an Rectamge object).

17 A very simple class - Rectangle
// Rectangle.java // only two simple instance variables: heigth and width // no methods public class Rectangle { public double height; public double width; } // end of class Rectangle

18 Explanations The file Rectangle.java contains the source code for the Rectangle class The class name and file name are the same There can only be one class declared as public in a file whose name is to be the same as the file name In principle there can be more than one class in a file but others are not declared as public When you use a development environment such as Eclipse, it creates one class for each file The extension of source code files is always java

19 Common Programming Error 1.1
Declaring more than one public class in the same file is a compilation error.

20 Explanations (cont.) When the program is compiled Java produces a byte code stored in a file named Rectangle.class The extension of byte codes are: class file name is: public_class_name.class in this example: Rectangle.class When executing – running - a program Java Virtual Machine (JVM) takes the byte codes and converts them into appropriate machine language of the platform. Then, CPU executes the instructions in the platform’s machine language

21 Explanations (cont.) The Rectangle defined in the file Rectangle.java has only two properties as hight and width. Both are real numbers declared a type double Every Rectangle object created – instantiated – from the Rectangle class can have a different hight and width variable These are called instance variables as every instance of Rectangle has these variables possibly with different values. these variables are declared with access modifier public – other classes can directly reach them and change them.

22 Explanations (cont.) Rectangle class is a template or blueprint for rectangles Rectangle name of the new class it is possible to declare instances of Rectangles, that is to create objects from the Rectangle class like that: Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); instance of a Rectangles refered by reference variables r1 and r2 Compare with declaring and inililizing a simple type int i =5; an integer varibale i is declered and initilized to 5

23 A Test Class // a test calss for creating Rectangle s and nanipulating TestRectangle .java public class TestRectangle { public static void main(String args[]) Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2); } // end of method main } // end of class TestRectangle

24 Explanations There are two classes in this program:
Rectangle and TestRectangle whose source codes are stored in files Rectangle.java and TestRectangle.java respectively. When the program is compiled the two source files are complied to files containing byte codes: Rectangle.class and TestRectangle.class respectively. When the program runs (is executed) Java Virtual Machine (JVM) takes the byte code instructions in .class files convert them into the machine language of the platform and execute instruction one by one

25 Explanations (cont.) There should only be one main method in only one of these files or classes usually called the test class or driver class. The instructions in the main method are executed one by one in a sequence naturally considering decision or iterations. In most of our applications objects from other classes are created, refered or manipulated in the main method of the test class.

26 what happends Default values for boolean type varaibles – false
In the previous program the following things happen in the main method in a sequence: first two Rectangle type objects are created and refered by two reference variables r1 and r2 respetively. Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); Initially the height and width of both rectangles have values 0.0 Look at the code of the Rectangle class – the two instance variables are declared without specifiying any initial value. public double height; public double width; The default values for numerical type simple instance variables are 0 for byte, short, int and long 0.0 for float and double Default values for boolean type varaibles – false for char type variables – null charcter \n0000’

27 in memory r1 and r2 refers to difremt Rectangle objects hegth 0.0 r1
width 0.0 r1 heigth 0.0 width 0.0 r2

28 what happends (cont.) r1.heigth and r2.heigth are different variables
r1.heigth: heigth of regtangle refered by reference r1 r2.height: heigth of regtangle refered by reference r2 stored in different memory locations can have different values...

29 What happends (cont.) using the . opperator it is possible to change and reach the instance variables of objects r1.height =3.0; assign for the variable heigfth of r1 objcet double area = r1.heigth*r1.width; area is decleared and initilized with the value of r1.height*r1width System.out .printf(“%f”,r1.height); print the higth of r1 the area or r1 can be printed withut using a variable is computed as System.out .printf(“area of r1 %10.2f”\n” ,r1.higth*r1.width); prints the area of rectangle refered by r1 without storing in a seperate variable such as area1

30 What happends (cont.) Note that test class can reach and change values of heigth and width variables of two Rectangle objects because in the Rectange class both heigth and width are declared as public objects created in other classes – here in the test class can change or reach these variables

31 Rectange as a reference
Note the word Rectangle appers two times in the statement Rectangle r1 = new Rectangle(); new Rectangle(); - creates a Rectangle object in memory Rectangle r1 = declares a reference variable of type Rectangle and assign the newly created Rectangle object to the (created on the right hand side of the =) to the referance variable Reference variables refer to objcts their values are not simple things such as integers or doubles but they hold the memoy address of objcts they are refering to.

32 The height and width variables of the first rectange is changed to 3
The height and width variables of the first rectange is changed to 3.0 and 4.0 respectively wia r1. Only the height variable of the second rectangle is changed via r2 to 5.0 . r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; the width of the second rectangle remains at 0.0

33 after changing values of variables
r1 and r2 refers to difremt Rectangle objects hegth 3 width 4 r1 heigth 5 width 0 r2

34 areas of the two rectangles are calculated and stored in area1 and area2 variables of type double.
double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; Both area1 and area2 are local variables in method main The values of area1 and area2 are printed System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2);

35 Deeper Look at Object Creation
Rectange r1 = new Rectangel(); actually three things happen here i - because of “=“ this is an assignment statement on the right hand side of assignment new Rectangle(); a Rectange object is created in memory whose instance variables heigth and width are taking defaulst values of 0.0 ii – on the left hand side - Rectangle r1 a Rectangle type reference variable whose name is r1 is declared iii – r1 is assigned to the newly created object r1 refers to the newly created objcet just created on the right hand side of assignment

36 Deeper Look at Object Creation (cont.)
Rectangel r1 = new Rectangel(); can be executed in two steps can be split into two Java statements step 1 Rectangle r1; r1 is a reference variable to a Rectangle type objcet here only a reference is declared but no object is created yet, r1 has the value null

37 Deeper Look at Object Creation (cont.)
if you write and try to execute r1.heigth error as r1 does not refer to any object yet – what is the value of r1 then? null if a reference variable exists but currently not refering to any objcect, its value is null.

38 creates a Rectangle object
step 2: r1 = new Rectangle(); new Rectangle(); creates a Rectangle object allocates memory for a Rectangle type objcet for holding instance variables r1 is already declared in step 1 (as a reference type) is assigned to the newly created object after step 2 is executed r1.height = 5.0; type of statements can be executed

39 r1 is a reference variable whose curent value is null
Rectangle r1; r1 is a reference variable whose curent value is null r1 null r1 = new Rectangle(); second step: r1 is a reference refering to the Rectangle object height 0.0 widtih 0.0 r1

40 new opperator Look at the reference_variable_name = new class name();
a constructor is executed usually initilize instance variables example: r1 = new Rectangle(); a Rectangle object’ instance variable hight, width are initilize to 0 doubles are initilize to 0 Look at the

41 returning to the test clas
Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2);

42 Assigning instance variables wia references
Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; r1 and r2 are refering different Rectangle objcects in memory

43 in memory r1 and r2 refers to difremt Rectangle objects hegth 3 r1
width 4 r1 heigth 5 width 0 r2

44 Values of Reference Variables
then perfrom the assignment r1 = r2; the value of r2 is assigned to r1 the new value of r1 becomes the value of r2 but what is the value of r2? – the Rectangle objects it refer to – the address of the object – not specifically its height or width.

45 so now r1’s value is also the same object r2 is refering
both r1 and r2 are refering to the same Rectangle object in memory So what happens to the first Rectangel object previously refered by r1 now, no reference variable is refering to the first Ractange object created.

46 in memory aftrer the assignment
r1 and r2 refering to the same Rectangle object hegth 3 width 4 r1 heigth 5 width 0 r2

47 after the assignment r1=r2; r1.heigth and r2.heigth has the value 5.0 as both reference variables refer to the same object, hight value r1.heigth = 6; System.out.println(r2.heigth); prints to the screen because we change the value via r1 from 5 to 6 and afrterwords refer it in println via r2

48 Garbage Collection As shown in the previous figure, after the assignment statement r1 = r2, r1 points to (refers to ) the same object referenced by r2. The object previously referenced by r1 is no longer referenced by any reference variable. This object is known as garbage. Garbage is automatically collected by JVM.

49 Garbage Collection, cont
TIP: If you know that an object is no longer needed, you can explicitly assign null to a reference variable for the object. The JVM will automatically collect the space if the object is not referenced by any refernece variable. Rectange r1 = new Rectange(); ... r1 = null;

50 Copying Variables of Primitive Data Types
for simple types such as int variables // declare and initilize two primitive types int i = 1 ,j = 2; i =j; //after this assignment both i and j are storing 2

51 Copying Variables of Primitive Data Types

52 Methods // method header
acces_modifier return_tyep method_name(parameter list) { // body of methhod begins statement(s); return expresion of type return_type; } // end of methods body method header includes acces modifier,return type, method name and parameter list body of the method contains several Java statements Note: there are nonstatic or instance methods

53 Methods (cont.) access_modifier: indicates the accesibility of the method from other classes – public , private, protected return_type: can be primitive types: int, double, boolean, ... reference type – returns an object from that type arrays or String are also reference types void: returns noting parameter list: comma seperated list of paramers type and name both simple types or references can be included in the list

54 Exampe lets add a method to the Rectangle class
to print the two properties of a regtangle the displayRectangle method does not take any parameter and does not return anything to its caller it process the two instance variables height and width

55 DisplayRect Method public class Rectangle { public double height;
public double width; public void displayRectangle() { System.out.println(“hight:”+higth ); System.out.println(“width:”+width ); } // end of displayRectangle method } // end of Rectangle class

56 Test class // a test calss for creating Rectangle s and nanipulating TestRectangle .java public class TestRectangl { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.height*r1.width; double area2 = r2.height*r2.width; System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,area2); r1.displayRectangle(); r2.displayRectangle(); } // end of method main } // end of class TestRectangle

57 what happens in class TestRectangle r1.displayRectangle();
invokes displayRectange mehtod over r1 the heigth and width variables of the object refered by r1 is printed r2.displayRectangle(); the heigth and width variables of the object refered by r2 is printed

58 what happens (cont.) to call it from another class
the instance variables height and width takes the values indicated by their object references value no need for the dot (.) operator to refer an instance variable or method from its own class reference name is not needed to call it from another class references are needed Exaple in the test claass r1.heigth, r2.display();

59 A methd returning a value
lets us add another method to calculate and return the area of a rectangle public class Rectangle { public double height; public double width; public double area() { double ar; ar = height*width; return ar; } // end of area method public void displayRectangle() { System.out.println(“hight:”+higth ); System.out.println(“width:”+width ); } // end of displayRectangle method } // end of Rectangle class

60 // a test calss for creating Rectangle s and nanipulating TestRectangle .java
public class TestRectangl { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.height = 3.0; r1.width = 4.0; r2.height = 5.0; double area1 = r1.area(); System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,r2.area()); r1.displayRectangle(); r2.displayRectangle(); } // end of method main } // end of class TestRectangle

61 More on Arguments and Parameters
Parameters specified in method’s parameter list Part of method header Uses a comma-separated list A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration. A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

62 object oriented v.s. procedural methods
if the area method were implemented in procedural programming it noramally requires two inputs – heigth and width of a rectange – calculates and returns the area as product of the two parameters public static double area(double h, double w) { return h*w; } in object oriented thinking the method has no parameters as it processes the instance variables of the rectangle over which the method is invoked

63 what happends: local iand instance variables
double area1 = r1.area(); when this statement is executed its right hand side invokes the area method via r1 so control passes to the Rectangle class’s area method the statements in area method are executed first, a local variable ar is declared in the area method but not initilized local variables when declared but not initlized has no default values this is one important difference betweeen local and instance variables instance variables such as heigth and width when declared but not initilized take default values – 0.0 (double type)

64 what happends (2) second, ar = height*width;
here rigth hand side is executed for the Rectangle object’s instance variables it is 3*4 when the method is invoked over r1 it is 5*0 when invoked over r2 rigth hand side value is assigned to local ar variable

65 what happends (3) third, return expression is evalueated and the value is returned to tis caller return ar; for the statement double area1 = r1.area(); 12 is returend to main and assigned to the area1 variable in main System.out. printf(“area of r2: %10.2f\n”,r2.area()); 0 is returned to printf method in main

66 local v.s. instance variables
Variables declared in the body of method or methdo parameters Called local variables Can only be used within that method Variables declared in a class declaration Called fields or instance variables Each object of the class has a separate instance of the variable static variables – discused in next chapter

67 Note on local variables
method parameters and variables declared in the body of methods are local variables For example: every call to the area method creates a new double varible ar in the memory space –for the area method every time retruning from the method all local variables including mehtod parameters are lost --- erased from memory of the method

68 area method – another implementation
the area method can simplly be coded as follows public double area() { return height*width; } // end of area method eliminating the local variable ar the return expression height*width is evalueated and a double value is returned to the caller

69 Preventing direct access
in the test class assignments like that r1.heigth =-10; assigns a meaningless value to heigth of r1 to protect such meaningless modifications direct access to instance varaibles from other classes are prohebited such as the testRectangle class in this example instance variables are declared with private access modifier rather than public to access or modify them public methods are introduced in their calsses called the set and get methods respectively.

70 get and set methods for example
setHeigth method provides a controlled modification for the heigth variable in case a negative value is tried to be assigned written once in class Rectange otherwise any class attemting to assign a value to heigth of a rectgangle should make this check if it is to be done within a method, it is natural that this method should be part of the Rectangle class

71 set method: a method taking parameters
lets add a set method to the Rectangle class for setting the heigth of a rectangle: public void setHeigth(double h) { if (h > 0.0) heigth = h; else height = 0.0; } // end of setHeight method

72 explanations the argument is assigned to the relevant parameter
void setHeigth(double h) takes a double type parameter parameters are local variables of methods when the method is called or invoked an argument is passed to the method parameter in this example h=10 it is possible to call the method like that r1.setHeigth(5+5); the argument is assigned to the relevant parameter the assignment is performed by JVM during the execution of the program – not by programmers method_parameter = argument h = 5+5

73 get method public double getHeigth() { return heght;
lets add a get method to the Rectangle class for returning the heigth of a rectangle: public double getHeigth() { return heght; } // end of setHeight method

74 explanations this get method inparticular and any get method in general does not get any parameters we need not provide extra nfromation to a get method as we did for set methods because get methods know what to retrun value of an instance variable for each instance variable it is wise to wrire a seperatge get method whose naem indicates what to do

75 private variables and set and get methods
private instance variables Cannot be accessed directly by other classes Use public set methods to alter the value Use public get methods to retrieve their values private keyword Used for most instance variables private variables and methods are accessible only to methods of the class in which they are declared Declaring instance variables private is known as data hiding

76 Access Modifiers public and private
Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods should be declared public. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

77 class Rectangle lets us add get and set methods to the Rectgangle class for height and width public class Rectangle { private double height; private double width; public double area() { return height*width; } // end of area method public void displayRectangle() { System.out.println(“hight:”+higth ); System.out.println(“width:”+width ); } // end of displayRectangle method

78 class Rectangle (cont.)
public void setHeigth(double h) { if (h > 0.0) heigth = h; else height = 0.0; } // end of setHeight method public double getHeigth() { return heigth; } // end of getHeigth method

79 class Rectangle (cont.)
public void setWidth(double w) { if (w > 0.0) width = w; else width = 0.0; } // end of setWidth method public double getWidth() { return width; } end of setWidth method } // end of Rectangle class

80 Test class using set and get methods
after creating two rectangle objects set thier heigths and widths invoking setHeigth and setWidth methods over r1 and r2 for the first and second rectangles respecively the area2 variable is calulated not by calling the area method but calling the getHeigth and getWidth methods over r2

81 class TestRectangle // a test calss for creating Rectangle s and nanipulating TestRectangle .java public class TestRectangl { public static void main(String args[]) { Rectangle r1 = new Rectangle(); Rectangle r2 = new Rectangle(); r1.setHeight(3.0); r1.setWidth(4.0); r2.setHeight(5.0); r2.setWidth(-10.0);// width of r2 is sst to 0.0 double area1 = r1.area(); double area2 = r2.getHeigth()*r2.getWidth(); System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,r2.area()); r1.displayRectangle(); r2.displayRectangle(); } // end of method main } // end of class TestRectangle

82 Software Engineering Observations
We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class’s fields anywhere in the class outside its method declarations, but scattering them tends to lead to hard-to-read code.

83 Good Programming Practice
Place a blank line between method declarations to separate the methods and enhance program readability.

84 2.7 Initializing Objects with Constructors
Initialize an object of a class Java requires a constructor for every class Java will provide a default constructor if none is provided Called when keyword new is followed by the class name and parentheses

85 Constructors When the objcets are created
most of their instance variables are initilized this can be done with such set methods as in the previous example In java there are spetial methods called constructors to do this initialization when the objcet is first created in memory they can perform other tasks as well but they are primarily used for initialization of instance variables

86 Creating Objects Using Constructors
new ClassName(); Examples: new Rectangle(); new Rectangle(5.0,4.0);

87 Default Constructor A class may be declared without constructors. In this case, a constructor with no parameters and an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class by the programmer.

88 unique nature of constructors
sama name with their class name called only after the new opperator – when an object is created cannot be called in statements following object creation otherwise similar to methods they do not return any thing but when declearing a constructor do not specify a return type that is do not make their return type void

89 no-argument Constructors
A constructor written by programmners with no parameters is referred to as a no-arg constructor. ·       Constructors must have the same name as the class itself. ·      Important if the programmer provides a constructor in the code of a class – no-argument or any other the defalut constructor provided by Java is out of operation

90 no-argument Constructors
A constructor written by programmners with no parameters is referred to as a no-arg constructor. ·       Constructors must have the same name as the class itself. ·       Constructors do not have a return type—not even void. ·       Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.

91 class Rectangle lets us add three constructors to Rectangle class
public class Rectangle { private double height; private double width; public Rectangle(double h,double w) { setHeight(h); setWidth(w); } // end of constuctor public Rectangle(double a) { setHeight(a); setWidth(a);

92 class Rectangle // no-argument constructor public Rectangle() {
setHeight(1.0); setWidth(1.0); } // end of no-argument constuctor public double area() { return height*width; } // end of area method public void displayRectangle() { System.out.println(“hight:”+higth ); System.out.println(“width:”+width ); } // end of displayRectangle method

93 class Rectangle (cont.)
public void setHeigth(double h) { if (h > 0.0) heigth = h; else height = 0.0; } // end of setHeight method public double getHeigth() { return heigth; } // end of getHeigth method

94 class Rectangle (cont.)
public void setWidth(double w) { if (w > 0.0) width = w; else width = 0.0; } // end of setWidth method public double getWidth() { return width; } end of setWidth method } // end of Rectangle class

95 Test class using set and get methods
creating three rectangle objects using three constructors a rectangle a square and a unit square Then changes the height and width of r1 and r2 using set and get methods

96 class TestRectangle // a test calss for creating Rectangle s and nanipulating TestRectangle .java public class TestRectangl { public static void main(String args[]) { Rectangle r1 = new Rectangle(2.0,4.0); Rectangle r2 = new Rectangle(5.0); Rectangle r3 = new Rectangle(); // no-argument constuctor r1.setHeight(3.0); r1.setWidth(4.0); r2.setHeight(5.0); r2.setWidth(-10.0);// width of r2 is sst to 0.0 double area1 = r1.area(); double area2 = r2.getHeigth()*r2.getWidth(); System.out. printf(“area of r1: %10.2f\n”,area1); System.out. printf(“area of r2: %10.2f\n”,r2.area()); r1.displayRectangle(); r2.displayRectangle(); } // end of method main } // end of class TestRectangle

97 Variable hiding in the same block
if the local variable and the instance variable have th same name local variable hides the instance variable use this modifier with the instance variable

98 The use of modifier this
public void setHeigth(double heigth) { if(heigth < 0.0) this.heigth = heigth; else this.heigth = 0.0; }

99 Explanations in this version of the setHeight method
name of the local variable – method parameter – and instance variable heigth are the same it is necessary to use the modifier this before the instance varible heigth to differentiate it from the local heigth otherwise every time heigth is used it refers to the local variable there is no way to reach the instance variable in the method

100 Explanations (cont.) The use of this is obtiaonal otherwise
any time an istance variable or an instance method is called within a class they can be refered by this

101 initial default values
Default initial value Provided for all fields not initialized Equal to null for reference types The default values for numerical type simple instance variables are 0 for byte, short, int and long 0.0 for float and double Default values for boolean type varaibles – false for char type variables – null charcter \n0000’

102 Initilizing Instance variables revisited
Instance variables are initilized by constructors It is also possible to provide a value whilse declaring an instance variable it is declared and assigned to that value Example: private duble heigth = 10.0; when creeating a Rectangel object before calling any consturctor its heigth instance variable is set to 10.0

103 Initilizing Instance variables revisited (cont.)
If a constructor modifies the value of the instance variable the default value or the value set in the decleration is changed

104 Examples public class Rectangle {
// every new Rectange has a heigth of 10.0 public double heigth = 10.0; // has a width of 0.0 public double width; // // different possible constructors

105 Examples (cont.) public Rectange(double heigth, double width) {
this.setWidth(width); } width is set to the parameter but heigth is left as 10.0

106 Examples (cont.) public Rectange(double a) { setHeigth(a);
this.setWidth(a); } use another construftor for squares both heigth and width are set to the parameter a the initial value of 10.0 for heigth is lost Note setHeigth is called without this but setWidth is called with modifer this

107 Examples (cont.) public Rectange() { heigth = 20.0; }
use no-argument constructor it masks the initial value of heigth and reset every heigth value to 20.0 no statments for setting width so it is left as 0.0

108 Summary class insance v.s. local variables
instance variables: simple or reference methods: constructors – special instance methods get and set methods for manipulating varibles insance v.s. local variables local variables - method pareters and declared in methods no default values lost after every exit form a methods instance variables – simple or reference initial or default values can be invoked by modifier this

109 Summary (cont.) Constuctors – special method access modifiers:
name same oas class only when objects are first created – instantiated no return type mostly public access modifiers: private – instance variables public – methods if needed to call from other classes public – get set methods modifier this: instance variables and method within the same class necessary if within a method laocal and instance variable has the same name

110 Note static variables and methods will be added

111 Sending simple types or references to methods
Illustrates the difference betwen methods with a simple type parameter and a reference type parameter In the test class TestExchange1 main method two integers are created (simple types) send to the exchange1 method – expected to interchang the,r values a beocmes 3, b beocmes 2

112 class TestExchange1 public calss TestExchange1 {
public static void main(String[] args) { int a = 2; int b = 3; System.out.printf( “in main before excahnge:%8d %8d\n”,a,b); exchange1(a,b); “in main after excahnge:%8d %8d\n”,a,b); } // end of method main

113 method exchange1 public static void exchange1(int x, int y) {
System.out.printf(“in exchange1 before excahnge of values:%8d %8d\n”,x,y); int temp = x; x = y; y = temp; System.out.printf(“in exchange1 after excahnge of values:%8d %8d\n”,x,y); } // end of method exchange1 } // end of class TestChange1

114 Explanation a and b simple int type variables values 2 and 3 respectively when send to exchange1 method as arguments in main JVM during execution performs the following assignments (not we as programmers) x = 3 and y = 2 upon a method call stack, first: its variables for its parameters are created in a seperate memoy location dedicated to the mehod – stack area – (parametera are local variables of the method as well) secand: argument values from the caller are assigned to these parameters by JVM (not by programmer) x = a and y = b that is x becomes 3, y becomes 2

115 Explanation (cont.) x and y in exchange1 are copied of a and b in main
the method exchange the values of x and y (the copies) not the original variables a and b when returning from the method to caller (main) all local variables are lost (x, y and temp) – erased from memory of method (strack area) In summery the exchange1 method cannot atchive the task of exchanging values of a and b in main but only the copies of them x and y.

116 class TestExchange2 public calss TestExchange2 {
public static void main(String[] args) { Int a = new Int(2); Int b = new Int(3); System.out.printf(“in main before excahnge:%8d %8d\n”,a.getVal(),b.getVal()); exchange2(a,b); System.out.printf(“in main after excahnge:%8d %8d\n”,a.getVal(),b.getVal()); } // end of method main

117 method exchange2 public static void exchange2(Int x, Int y) {
System.out.printf(“in exchange1 before excahnge of values:%8d %8d\n”,x.getVal(),y.getVal()); int temp = x.getVal(); x.setVal(y.getVal()); y.setVal(temp); System.out.printf(“in exchange1 after excahnge of values:%8d %8d\n”, x.getVal(),y.getVal()); } // end of method exchange2 } // end of class TestExchange2

118 class Int public class Int { private int val; public Int(int v) {
val = v; } public int getVal() { return val; public void setVal(int v) { } // end of class Int

119 Explanation a and b Int type variables references refering to Int type objects holding 2 and 3 as values in them. Now they are not simple int types when send to exchange2 method as arguments in main JVM during execution performs the following assignments (not we as programmers) x = a and y = b upon a method call – call of exchange2 - here first: x and y – two reference type variables are created as method parameters secand: argument values from the caller are assigned to these parameters by JVM (not by programmer) x = a and y = b that is value of a is assigned to x and value of b is to y

120 Explanation (comt.) but what are the values of a and b?
simply 2 and 3 no! as references they are refering to Int type objects holding 2 and 3 as their values so x is also refering to what a is refering y is refering to what b is refering although objects are created in methd main they are passed to the other method exchange2 with references x and y

121 Explanation (comt.) x and y in exchange2 are copied of a and b in main – in terms of memoy addresses – in this case they refer to the same objects in the same memoy addresses as a and b are refering the method extracts the value of the object refered by x to a simple int type variable temp, get the value of the object refered by y and set it as the value of the object refered by x so exchange the values contained within the objects via x and y

122 Explanation (comt.) when returning from the method to caller (main)
again all local variables are lost (x, y and temp) – erased from memory of method exchange2 (strack area) In this case x and y disappears but what they do on the objects they refer is permenent because they reach the same objects as a and b are refering and able to exchange the content of them from another method – exchange2

123 class TestExchange3 // Test class is the same a TestExclass2
// except send a and b to exchange3 public calss TestExchange3 { public static void main(String[] args) { Int a = new Int(2); Int b = new Int(3); System.out.printf(“in main before excahnge:%8d %8d\n”,a.getVal(),b.getVal()); exchange3(a,b); System.out.printf(“in main after excahnge:%8d %8d\n”,a.getVal(),b.getVal()); } // end of method main

124 method exchange3 public static void exchange3(Int x, Int y) {
System.out.printf(“in exchange1 before excahnge of values:%8d %8d\n”,x.getVal(),y.getVal()); Int temp = x; // object form Int class x = y; y = temp; System.out.printf(“in exchange1 after excahnge of values:%8d %8d\n”, x.getVal(),y.getVal()); } // end of method exchange3 } // end of class TestExchange3

125 Explanations In exchange3 method
temp is a reference varible whose value is the same as x s value the object refered by x after executing temp = x; both x and temp are refering to the same object x = y; valueof x: object refered by x is the smae as valueof y object refered by y

126 Explanations finally y = temp; y refers to the same object as temp
The local variables x, y and temp s values change the objects they are refering changes in exchange3 but not the integer type number within these objects Nogt sucessful in exchaning content of objects

127 Example: rational numbers
Write a rational number class having nominator and denominator of a rational number as its two instance variables Having addition, substract, multiplyi and division methods These methods should be invoked over one rational number, taking the other as a parameter and return the result of the opperation as a new rational number For example Rational r1 = new Rational(2,3); Rational r2 = new Rational(3,4); Rational r3 = r1.add(r2);

128 Mathematical representgation
Mathematically ratioanal numbers can be represented either as compund form or as whole and fraction form 4/3 is in compund form but 1 1/3 is in whole and faction form in the class internally we hold all rational numbers in the compund form but allow to create them in the whole form as well

129 Programming Two classes: a Rational class and a Test class
Rational: a blueprint for rational numbers in compund form two constructors set, get methods for manipulating instance variables add method for adding two rational numbers display method for displaying numerator and denumerator of a rational number to the command prompt TestClass: creates rational numbers and illustrate use of its methods

130 class Rational public class Rational {
private int num; // numerator of the number private int denum; // denumarator of the number // two and three parameter constructors public Rational(int n, int d) { this.setNum(n); // use of this is optional. You can call any of these setDen(d); // methods with or without this } // end of two parameter constructor public Rational(int w, int n, int d) { setNum(w*d+n); this.setDen(d); } // end of three parameter constructor

131 class Rational (cont.) public void setNum(int num) {
this.num = num; // use of this is required to because name of // parameter and instance variable have the same name } // end of method setNum public void setDen(int d) { if (d == 0 ) den = 1; // we set it to one in case of 0 denominator else den = d; } // end of method setDen

132 class Rational (cont.) public int getNum() { return nun;
} // end of method getNum public int getDen() { return den; } // end of method getDen public void display() { System.out.printf(“%8d / %8d\n”,num,den); }

133 class Rational (cont.) public Rational add(Rational r) { int numRes =
num*r.den+r.num*den; int denRes = den*r.den; Rat result = new Rational(numRes,denRes); return result; } // end of method add } // end of class Rational

134 class TestRational public class TestRational {
public static void main(String[] args) { /* creates two rational number objects using the two constructors refered by reference variables r1 and r2 respectively */ Rational r1 = new Rational(4,3); Rational r2 = new Rational(1,1,4); /* invoking the add method over one of them r1 meating the resulting sum with reference r3 Rational r3 = r1.add(r2); r1.display(); r2.display(); r3.display(); } // end of method main } // end of class TestRational

135 explanations Here in the test class add method is invoked on r1
Taking r2 as an argumnet It is to add r1 and r2 and return a reference type Rational which is assigned to r3 reference variable in main public Rational add(Rational r) { int numer = ....; int denom = ...; Rational result new Rational(numer,denom); return result; }

136 explanations (cont.) When the method is called for an object in a test class r1.add(r2); method parameter is assinged argument r = r2 by Java Virtual Machine (JVM) value of r2 (a Rational object) is passed to method parameter r both r and r2 refer to the same Rational object in memory but r is in stack araa of add method r2 is in stack area of main method

137 explanations (cont.) when retrun statement of the add method is executed it will return a Rational objcet created and initilized in the add methodr3 Rational r3 = r2.add(r1); r3 is refering the the objcet created in the mehtod JVM performs the assignement r3 = result – not the programmer all local variables should be lost includingf result the new Rational object created in add would be lost if not assinged to r3 in other words if not met by r3

138 set and get methods an exception
within a class even private variables of the object of the same class can be reached without get or set methods int numRes = num*r.den+r.num*den; int denRes = this.den*r.den; could be written using get methds int numRes = this.num*r.getDen()+r.GetNum()*this.den; int denRes = this.den*r.getDen();

139 add method: another varsion
Onther version of the add method without a refernce variable result in the return statement create the new Rational object and return it what are the local variables in the two versions of the add method? What happens to these variables after exiting from the method public Rational add(Rational r1) { int numer = ....; int denom = ...; returnn new Rational(numer,denom); }

140 Exercises Write a method for testing the equality of two rational numbers Note that 1/3 and 2/6 are equal Testing the equality of numertator and denominator is not enough Similarly write a greaterThen method testing whether a rational number is greater then the other These methods should be invoked over one of the reational numbers and tekes the other as a parameter Both methods should return boolean variables

141 Illustration: Object do not have names
Perform the task done in main by gradually eleminating the three references to the three rational numbers A very bad styled of programming end up with a very unreadable source code but shows that objects – in this application - the three rational numbers do not haved names initially we give names to reference variables refering to these objects r1, r2 and r3 but gradually eliminate these reference variables in three stages in the test classes from TestRational3 – with three references to TestRational0 – with no reference variables

142 an observation during the execution of a Java program
new Rational(4,3); creates a Rational object in memory without refering by a Rational type reference since it is not refered by a reference variable , in the subsequent Java statment, it is a candidate to go to garbage

143 with three references public class TestRational3 {
public static void main(String[] args) { /* creates two rational number objects using the two constructo refered by reference variables r1 and r2 respectively */ Rational r1 = new Rational(4,3); Rational r2 = new Rational(1,1,4); /* invoking the add method over one of them r1 meating the resulting sum with reference r3 Rational r3 = r1.add(r2); /* display r3 */ r3.display(); } // end of method main } // end of class TestRational

144 eliminating r2 public class TestRational2 {
public static void main(String[] args) { /* creates first rational number objects using the two parameter constructors refered by reference variable r1 */ Rational r1 = new Rational(4,3); /* invoking the add method over r1 creating the second rational as an object and sending to the add method as an argument without refering by a reference variable Rational r3 = r1.add(new Rational(1,1,4)); r3.display(); } // end of method main } // end of class TestRational

145 Explanation Rational r3 = r1.add(new Rational(1,1,4));
argument of the add method is a new Rational object created and directly send to the add method as an argument without refering by a Rational type reference as in version 3 JVM performs the assignment r= new Rational(1,1,4) the method parameter r gets the newly createded object

146 eliminating r2 and r1 public class TestRational1 {
public static void main(String[] args) { /* creates a rational number object wsithout refering by a reference immediately after creating the object call the add method over the object creating the second rational as an object and sending to the add method as an argument without refering by a reference variable */ Rational r3 = new Rational(4,3).add(new Rational(1,1,4)); r3.display(); } // end of method main } // end of class TestRational

147 Explanation Rational r3 = new Rational(4,3).add(new Rational(1,1,4));
a new Rational object is created by the first new without refering by a reference (r1) as soon as it is created in memory, add method is invoked over this object after the execution of this statment the object – first Rational object goes to garbage

148 eliminating r2 , r1 smf t3 public class TestRational0 {
public static void main(String[] args) { /* creates a rational number object wsithout refering by a reference immediately after creating the object call the add method over the object creating the second rational as an object and sending to the add method as an argument without refering by a reference variable the add method returns a Rational object instad of refering the reuslting object with a reference, immediately call the display method to print the sum to command prompt */ new Rational(4,3).add(new Rational(1,1,4)).display(); } // end of method main } // end of class TestRational

149 Explanation new Rational(4,3).add(new Rational(1,1,4)).display();
execution of the add method returns a Rational object – not met by any reference on the Rational object holding the result of addition directly the display method is called after the execution of the statment all three objects go to garbage

150 methods invokation over objects
Methods are invoked over objects it is possible to invoke a method over object that are not refered by any reference new Rational(4.3).display(); a new Rational object is created and immediately display method is invoked over it after the exectution of this Java statment, it is a candidate to garbage

151 methods invokation over objects (cont.)
This is also possible Rational r1 = new Rational(4.3); Rational r2 = new Rational(1,1.3); r1.add(r2).display(); add method returns a Rational object without refering it display method is invoked over the resulting Rational object the result of addition is candidate to garbage

152 methods invokation over objects (cont.)
MThis is also possible Rational r1 = new Rational(4.3); r1.add(new Rational(1.1.3)); add method is invoked over the first Rational object new refered by r1 but the rerutning object is not met by a Rational reference type so the retruning object is a csndidate to garbage

153 Importnat concepts from the example
Objcets do not have names memory locations refered by referance variables these references have names objects unless refered by references, candidates to go to garbage during the execution of subsequent statments Methods are executed over objects either via references or directly on objectgs

154 With default constructor
The same initialization can be atchived public class Circle { double radius =10; // no-arg constructor is not provided Other methods Constactors with parameters } // end of class Circle İn the CircelTest class Circle c = new Circle(); Criates a Circle objcet with a radius of 10

155 Quiz #1 Summer 2010: A life simulation program
Extension of the Quiz or Homework question in Fall 2010 simple life simulation program Illustrate the concept of private constructors Another use of this How to use this when passing the same object to a method

156 Quiz #1 Summer 2010: A life simulation program
Write the java program for the following problem: Create a Person class having name,gender, mother and father as instance variables. Gender is an int type variable: 0 for males and 1 for females Constructor: Write a constructor having two parameters: gender and name and creates a person object. Used in the test class for creating first humans whose mothers’ and fathers’ are not known A private constructor: Write another constructor having four parameters: gender and name and creates a person object. Used in ihe born method for the objectrs whose mothers and fathers are known

157 Quiz #1 Summer 2010: A life simulation program
Born method: Write a born method running over females (as the mother of the child), taking three parameters: a male object as the father of the child, name and gender of the child. The born method returns the a new person object if the genders of mother and father are corect otherwise returns null (return null;). Do not write any other method for the Person class. In the test class create two persons: a father and a mother and illustrate the use of the born method The child returned from the born method should be assigned to another person object in the test class as well.

158 Person class public class Person { private String name;
private int gender; private Person mother, father; // default null public Person(String n, int g ) { name = n; gender = g; // mother and father remains null } private Person(String n, int g, Person m, Person f ) { mother = m; father = f;

159 Person class (cont.) public Person born(String n, int g, Person f) {
/* creaate a Person objcect using the private constructor. The four parameter constructor can only be used within the class methods to create Persons objects (childeren whose mothers and fathers are known) Pass the mother as the third parameter using this */ Person child = null; if(gender == 0 and f.gender == 1) child = new Person(n,g,this,f); return child; }

160 Test class public class Test {
public static void main(String args[]) { // use public constuctor when creating initial Persons Person pf = new Person(“Adem”,1); Person pm = new Person(“Havva”,0); // in the born method the private constructor will bu used Person pchild = pm.born(“Habil”,1,pf); } // end method main } // end class Test

161 explanations child = new Person(n,g,this,f);
third and forth parameters of the private constructor is of type Person father is directly passed to the forth parameter the born method is invoked over a mother object so every time it is executed wtihin the method this is a reference to the object the method is invoked while method is executing over an object it can ferfer to the objet itself

162 Examples of creating Circle objcets
new Circle(10); Criates a Circle objcet runs the constructor – radius is 10 But no referans variable is assigned to this object so İt is removed by the garbage collector Double a = new Circle(10).area(); Criate a Circle objcet with an initial radius of 10 İnvoke its araa method Assign the area to the double variable a Again no referans variable criated so the object is useless in subsequent statements and will be collected

163 Examples of creating Circle objcets
System.out.printf(“%f”,new Circle(10).area()); Criate a Circle objcet with an initial radius of 10 İnvoke its araa method Send the numerical value to the printf method the area is printed Again no referans variable criated so the object is useless in subsequent statements and will be collected

164 The null Value If a data field of a reference type does not reference any object, the data field holds a special literal value, null.

165 Accessing Objects Referencing the object’s data: objectRefVar.data
e.g., myCircle.radius Invoking the object’s method: objectRefVar.methodName(arguments) e.g., myCircle.getArea()

166 Caution Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5)) to invoke a method in the Math class. Can you invoke getArea() using Circle1.getArea()? The answer is no. All the methods used before this chapter are static methods, which are defined using the static keyword. However, getArea() is non-static. It must be invoked from an object using objectRefVar.methodName(arguments) (e.g., myCircle.getArea()). More explanations will be given in Section 7.6, “Static Variables, Constants, and Methods.”

167 Reference Data Fields The data fields can be of reference types. For example, the following Student class contains a data field name of the String type. public class Student { String name; // name has default value null int age; // age has default value 0 boolean isScienceMajor; // isScienceMajor has default value false char gender; // c has default value '\u0000' }

168 Default Value for a Data Field
The default value of a data field is null for a reference type, 0 for a numeric type, false for a boolean type, and '\u0000' for a char type. However, Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { Student student = new Student(); System.out.println("name? " + student.name); System.out.println("age? " + student.age); System.out.println("isScienceMajor? " + student.isScienceMajor); System.out.println("gender? " + student.gender); }

169 Example Java assigns no default value to a local variable inside a method. public class Test { public static void main(String[] args) { int x; // x has no default value String y; // y has no default value System.out.println("x is " + x); System.out.println("y is " + y); } Compilation error: variables not initialized

170 Classes

171 A class may be declared without constructors
A class may be declared without constructors. In this case, a no-arg constructor with an empty body is implicitly declared in the class. This constructor, called a default constructor, is provided automatically only if no constructors are explicitly declared in the class.

172 Constructors Constructors are a special kind of methods that are invoked to construct objects. Circle() { } Circle(double newRadius) { radius = newRadius;

173 3.3 Declaring a Class with a Method and Instantiating an Object of a Class
Each class declaration that begins with keyword public must be stored in a file that has the same name as the class and ends with the .java file-name extension.

174 Class GradeBook keyword public is an access modifier
Class declarations include: Access modifier Keyword class Pair of left and right braces

175 3.4 Declaring a Method with a Parameter
Method parameters Additional information passed to a method Supplied in the method call with arguments

176 Software Engineering Observation 3.1
Normally, objects are created with new. One exception is a string literal that is contained in quotes, such as "hello". String literals are references to String objects that are implicitly created by Java.

177 More on Arguments and Parameters
Parameters specified in method’s parameter list Part of method header Uses a comma-separated list

178 Common Programming Error 3.2
A compilation error occurs if the number of arguments in a method call does not match the number of parameters in the method declaration.

179 Common Programming Error 3.3
A compilation error occurs if the types of the arguments in a method call are not consistent with the types of the corresponding parameters in the method declaration.

180 3.5 Instance Variables, set Methods and get Methods
Variables declared in the body of method Called local variables Can only be used within that method Variables declared in a class declaration Called fields or instance variables Each object of the class has a separate instance of the variable

181 Access Modifiers public and private
private keyword Used for most instance variables private variables and methods are accessible only to methods of the class in which they are declared Declaring instance variables private is known as data hiding Return type Indicates item returned by method Declared in method header

182 Software Engineering Observation 3.3
Precede every field and method declaration with an access modifier. As a rule of thumb, instance variables should be declared private and methods should be declared public. (We will see that it is appropriate to declare certain methods private, if they will be accessed only by other methods of the class.)

183 Good Programming Practice 3.1
We prefer to list the fields of a class first, so that, as you read the code, you see the names and types of the variables before you see them used in the methods of the class. It is possible to list the class’s fields anywhere in the class outside its method declarations, but scattering them tends to lead to hard-to-read code.

184 Good Programming Practice 3.2
Place a blank line between method declarations to separate the methods and enhance program readability.

185 GradeBookTest Class That Demonstrates Class GradeBook
Default initial value Provided for all fields not initialized Equal to null for Strings

186 set and get methods private instance variables
Cannot be accessed directly by clients of the object Use set methods to alter the value Use get methods to retrieve the value

187 3.7 Initializing Objects with Constructors
Initialize an object of a class Java requires a constructor for every class Java will provide a default no-argument constructor if none is provided Called when keyword new is followed by the class name and parentheses

188 Error-Prevention Tip 3.1 Unless default initialization of your class’s instance variables is acceptable, provide a constructor to ensure that your class’s instance variables are properly initialized with meaningful values when each new object of your class is created.

189 Visibility Modifiers and Accessor/Mutator Methods
By default, the class, variable, or method can be accessed by any class in the same package. public The class, data, or method is visible to any class in any package. private The data or methods can be accessed only by the declaring class. The get and set methods are used to read and modify private properties.

190 The private modifier restricts access to within a class, the default modifier restricts access to within a package, and the public modifier enables unrestricted access.

191 NOTE An object cannot access its private members, as shown in (b). It is OK, however, if the object is declared in its own class, as shown in (a).

192 Why Data Fields Should Be private?
To protect data. To make class easy to maintain.

193 Example of Data Field Encapsulation
Circle3 TestCircle3 Run

194 Passing Objects to Methods
Passing by value for primitive type value (the value is passed to the parameter) Passing by value for reference type value (the value is the reference to the object) TestPassObject Run

195 The Account class //Account.java public class Accoun {
private double balance; public Account(String ao, String accNo, double initial) { setBalance(initial); } // end constructor

196 Account class (cont.) public void deposit(double amount) {
balance+=amount; } // end of method deposit public double getbalance() { return balance; } public void setbalance(double balance) { if(balance>=0) this.balance = balance; // this is required to distinguish instance and local variables else this.balance = 0.0; } // end of method setbalance } // end of class Account

197 A Test class using the Account class
import java.util.Scanner; public class AccountTest { public static void main( String args[] ) { Account account1 = new Account( ); Account account2 = new Account( ); // display initial balance of each object System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );

198 Test class (cont.) Scanner input = new Scanner( System.in );
double depositAmount; System.out.print( "Enter deposit amount for account1: " ); // prompt depositAmount = input.nextDouble(); System.out.printf( "\nadding %.2f to account1 balance\n\n", depositAmount ); account1.credit( depositAmount ); // add to account1 balance System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );

199 Test class (cont.) Scanner input = new Scanner( System.in );
double depositAmount; System.out.print( "Enter deposit amount for account1: " ); // prompt depositAmount = input.nextDouble(); System.out.printf( "\nadding %.2f to account1 balance\n\n", depositAmount ); account1.credit( depositAmount ); // add to account1 balance System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() ); System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );

200 Output account1 balance: $50.00 account2 balance: $0.00
Enter deposit amount for account1: 25.53 adding to account1 balance account1 balance: $75.53 Enter deposit amount for account2: adding to account2 balance account2 balance: $123.45

201 Adding other methods Withdraw money from an account
Add two methods to the account class Withdraw money from an account Transfer money from one account to another account withdraw money from the argument and transter it to the account on which the method is invoked.

202 Withdraw method public void withdraw(double money) {
if (money < balance ) balance -=money; } // end of method withdraw

203 Withdraw method another version
/* sending a bolean message to the caller indicating weather the withdraw operation is succesfull or not */ public boolean withdraw(double money) { if (money < balance ) { balance -=money; return true; } return false; } // end of method withdraw

204 Transfering money // objcets as parameters
public boolean tramsfer(Account acc, double money) { if (money < acc.getbalance() ) { acc.withdraw(money); balance += money; // or deposit(money); use deposit method of Account return true } return false } // end of method transfer

205 Part of code of the test class
// create two accounts Account a1 = new Account(100.0); Account a2 = new Account(200.0); // get money from the user double money = input.nextDouble(); // transfer money from a1 to a2 a2.transfer(money,a1); /* invoke the transfer method on a2 the account money to be transfered Send a1 as an argument to the method

206 Another example: The Date class Exercise 3.15
Design a date class with attrubutes year, month,day as integers Design its constructors Set and get methods A print method printing in a format Write a test class DateTest create verious Dates objcets and print them

207 public class Date { // default values of instance variables private int year= 1970.month=1,day=1; public Date {int day,int month,int year) { setYear(year); setMonth(month); setDay(day); }

208 public void setYear(int year)
{ if (year > 0 ) this.year = year; } public void setMonth(int month) if (month > 0 && month <= 12) this.month = month; // you can do the setDay method

209 public int getYear(); { return year; } // do the ohhers public void printDate(); // fill the body of this method

210 Exercises This is more usefull in some applications
Write an isEqual method indicating two days are equal or not This is more usefull in some applications Write a isBefore method indicating wheter a day is before the other Call the isEqual and isBefore method like that date1.isBefore(date2); Day cumhuriyetBayramı = new Day(2017,10,29); Day cocukBayramı = new Day(2017,4,23); cumburieytBayramı.isBefore(cocukBayramı); returns true if argument – cocukBayramı - is before then the objcet on which the method is called – cumhuriyetBayramı.

211 Exercises Write a method calculating the number of days between two days considering that Fabrivary is 29 days in leap years Write a method indicating whether a day is a weekend or not Write a method returning the weekday of a given day either as strings or numbers say “Monday” or 1 for “Monday”

212 Other exercises In Deitel and Deitel 3.12-3.15
We solved some parts of 3.12 and 3.15 Refer to exercise 8.17 for rational numbers Refer to exercis 8.16 for date class

213 Other exercises Enhenced circle class
For the circle class we did in class add position variables holding the position x and y coordinates of he circle Create circles with constructors Write mehods indicating whether two circles are separeded, tangent to each other, one is inside the other or overlaping

214 0.0 X axis y axis

215


Download ppt "Introduction to Classes and Objects"

Similar presentations


Ads by Google