27
9 Working with the Java Class Library 9.1 Objectives In this section, we will introduce some basic concepts of object-oriented programming. Later on, we will discuss the concept of classes and objects, and how to use these classes and their members. Comparison, conversion and casting of objects will also be covered. For now, we will focus on using classes that are already defined in the Java class library, we will discuss later on how to create your own classes. At the end of the lesson, the student should be able to: • Explain object-oriented programming and some of its concepts • Differentiate between classes and objects • Differentiate between instance variables/methods and class(static) variables/methods • Explain what methods are and how to call and pass parameters to methods • Identify the scope of a variable • Cast primitive data types and objects • Compare objects and determine the class of an objects 9.2 Introduction to Object-Oriented Programming Object-Oriented programming or OOP revolves around the concept of objects as the basic elements of your programs. When we compare this to the physical world, we can find many objects around us, such as cars, lion, people and so on. These objects are characterized by their properties (or attributes) and behaviors. With these descriptions, the objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods. 9.3 Classes and Objects 9.3.1 Difference Between Classes and Objects In the software world, an object is a software component whose structure is similar to objects in the real world. Each object is composed of a set of data (properties/attributes) which are variables describing the essential characteristics of the object, and it also consists of a set of methods (behavior) that describes how an object behaves. Thus, an object is a software bundle of variables and related methods. The variables and methods in a Java object are formally known as instance variables and instance methods to distinguish them from class variables and class methods. The class is the fundamental structure in object-oriented programming. It can be thought of as a template, a prototype or a blueprint of an object. It consists of two types of members which are called fields (properties or attributes) - Fields specifiy the data types defined by the class. and methods., while methods specify the operations. An object is an instance of the class. 9.3.2 Encapsulation Encapsulation is the method of hiding certain elements of the implementation of a certain class. By placing a boundary around the properties and methods of our objects, we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways. We can prevent access to our object's data by declaring them declaring them in a certain way such that we can control access to them.

Java Class Library

Embed Size (px)

Citation preview

Page 1: Java Class Library

9 Working with the Java Class Library9.1 ObjectivesIn this section, we will introduce some basic concepts of object-oriented programming.Later on, we will discuss the concept of classes and objects, and how to use these classesand their members. Comparison, conversion and casting of objects will also be covered.For now, we will focus on using classes that are already defined in the Java class library,we will discuss later on how to create your own classes.At the end of the lesson, the student should be able to:• Explain object-oriented programming and some of its concepts• Differentiate between classes and objects• Differentiate between instance variables/methods and class(static)variables/methods• Explain what methods are and how to call and pass parameters to methods• Identify the scope of a variable• Cast primitive data types and objects• Compare objects and determine the class of an objects9.2 Introduction to Object-Oriented ProgrammingObject-Oriented programming or OOP revolves around the concept of objects as thebasic elements of your programs. When we compare this to the physical world, we canfind many objects around us, such as cars, lion, people and so on. These objects are characterized by their properties (or attributes) and behaviors.

With these descriptions, the objects in the physical world can easily be modeled assoftware objects using the properties as data and the behaviors as methods.9.3 Classes and Objects9.3.1 Difference Between Classes and Objects

• In the software world, an object is a software component whose structure is similar to objects in the real world.

• Each object is composed of a set of data (properties/attributes) which are variables describing the essential characteristics of the object,

• and it also consists of a set of methods (behavior) that describes how an object behaves. • Thus, an object is a software bundle of variables and related methods. • The variables and methods in a Java object are formally known as instance variables and

instance methods to distinguish them from class variables and class methods.• The class is the fundamental structure in object-oriented programming. It can be thought of as a

template, a prototype or a blueprint of an object.▪ It consists of two types of members which are called

• fields (properties or attributes) - Fields specifiy the data types defined by the class.

• and methods., while methods specify the operations. • An object is an instance of the class.

9.3.2 EncapsulationEncapsulation is the method of hiding certain elements of the implementation of a certain class. By placing a boundary around the properties and methods of our objects, we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways.We can prevent access to our object's data by declaring them declaring them in a certain way such that we can control access to them.

Page 2: Java Class Library

Problem: Create a program that will display a welcome message to the GradeBook user in the format: “Welcome to the Grade Book!”

1 // Fig. 3.1: GradeBook.java2 // Class declaration with one method.34 public class GradeBook5 {6 // display a welcome message to the GradeBook user7 public void displayMessage()8 {9 System.out.println( "Welcome to the Grade Book!" );10 } // end method displayMessage1112 } // end class GradeBook

Fig. 3.1 | Class declaration with one method.-------------------------------------------------------1 // Fig. 3.2: GradeBookTest.java2 // Create a GradeBook object and call its displayMessage method.34 public class GradeBookTest5 {6 // main method begins program execution7 public static void main( String args[] )8 {9 // create a GradeBook object and assign it to myGradeBook10 GradeBook myGradeBook = new GradeBook();1112 // call myGradeBook's displayMessage method13 myGradeBook.displayMessage();14 } // end main1516 } // end class GradeBookTest

Output:

Fig. 3.2 | Creating an object of class GradeBook and calling its displayMessage method.

Classes provide the benefit of reusability. Software programmers can use a class overand over again to create many objects.

Welcome to the Grade Book!

Page 3: Java Class Library

9.3.3 Class Variables and Methods• class variables - are variables that belong to the whole class. This means that it has the same

value for all the objects in the same class. They are also called static member variables.

public class Sum{ public static void main(String args[]) { int num1=2; int num2= 3; int sum=0; sum = num1 + num2; System.out.println(“The sum is “, sum); }}

9.3.4 Class InstantiationTo create an object or an instance of a class, we use the new operator. For example, if you want to create an instance of the class String, we write the following code,

String str2 = new String(“Hello world!”);

or also equivalent to,String str2 = "Hello";

Figure 9.1: Classs Instantiation• The new operator allocates a memory for that object and returns a reference of that

memory location to you. When you create an object, you actually invoke the class' constructor. The constructor is a method where you place all the initializations, it has the same name as the class.

import java.util.Scanner;public class Sum{ public static void main(String args[]) {

Page 4: Java Class Library

Scanner input = new Scanner(System.in); int num1=0; int num2 =0; int sum=0; System.out.println(“Enter the first number: ”); num1= input.nextInt(); System.out.println(“Enter the second number: ”); num2= input.nextInt(); sum = num1 + num2; System.out.println(“The sum is “, sum); }}9.4 Methods9.4.1 What are Methods and Why Use Methods?In the examples we discussed before, mostly we only have one method, and that is the main() method. In Java, we can define many methods which we can call from different methods.

• A method is a separate piece of code that can be called by a main program or any othermethod to perform some specific function.

The following are characteristics of methods:• It can return one or no values• It may accept as many parameters it needs or no parameter at all. Parameters arealso called function arguments.• After the method has finished execution, it goes back to the method that called it.Now, why do we need to create methods? Why don't we just place all the code inside one big method? The heart of effective problem solving is in problem decomposition. We cando this in Java by creating methods to solve a specific part of the problem. Taking a problem and breaking it into small, manageable pieces is critical to writing large programs.

9.4.2 Calling Instance Methods and Passing Variables

To call an instance method, we write the following,

nameOfObject.nameOfMethod( parameters );

Example:

1 // Fig. 3.4: GradeBook.java2 // Class declaration with a method that has a parameter.34public class GradeBook5 {6 // display a welcome message to the GradeBook user7 public void displayMessage( )8 {9 System.out.printf( "Welcome to the grade book for\n%s!\n",10 courseName );11 12 } // end method displayMessage

Page 5: Java Class Library

13 } // end class GradeBookFig. 3.4 | Class declaration with one method that has a parameter.

Page 6: Java Class Library

1 // Fig. 3.5: GradeBookTest.java2 // Create GradeBook object and pass a String to3 // its displayMessage method.4 import java.util.Scanner; // program uses Scanner56 public class GradeBookTest7 {8 // main method begins program execution9 public static void main( String args[] )10 {11 // create Scanner to obtain input from command window12 Scanner input = new Scanner( System.in );1314 // create a GradeBook object and assign it to myGradeBook15 GradeBook myGradeBook = new GradeBook();1617 // prompt for and input course name18 System.out.println( "Please enter the course name:" );19 String nameOfCourse = input.nextLine(); // read a line of text20 System.out.println(); // outputs a blank line2122 // call myGradeBook's displayMessage method23 // and pass nameOfCourse as an argument24 myGradeBook.displayMessage( nameOfCourse );25 } // end main2627 } // end class GradeBookTest

Fig. 3.5 | Creating a GradeBook object and passing a String to its displayMessage method.Output :

Please enter the course name:CS101 Introduction to Java ProgrammingWelcome to the grade book forCS101 Introduction to Java Programming!

-------------------

• Line 24 calls myGradeBooks’s displayMessage method. • The variable nameOfCourse in parentheses is the argument that is passed to method

displayMessage so that the method can perform its task. • The value of variable nameOfCourse in main becomes the value of method displayMessage’s

parameter courseName in line 7 of Fig. 3.4. • When you execute this application, notice that method displayMessage outputs the name you

typeas part of the welcome message (Fig. 3.5).

• Method nextLine reads characters typed by the user until the newline character is encountered, then returns

Page 7: Java Class Library

a String containing the characters up to, but not including, the newline. The newline character is discarded.

• Parameter - additional information • A method can require one or more parameters that represent additional information it needs to

perform its task. • A method call supplies values—called arguments—for each of the method’s parameters.

As you know, a method is invoked by a method call, and when the called method completes its task, it returns either a result or simply control to the caller. An analogy to this program structure is the hierarchical form of management (Figure 6.1).

• A boss (the caller) asks a worker (the called method) to perform a task and report back (return) the results after completing the task.

• The boss method does not know how the worker method performs its designated tasks.• The worker may also call other worker methods, unbeknown to the boss. This “hiding” of

implementation details promotes good software engineering.Figure 6.1 shows the boss method communicating with several worker methods in a hierarchical manner. The boss method divides its responsibilities among the various worker methods. Note that worker1 acts as a “boss method” to worker4 and worker5.

9.4.3 Passing Variables in MethodsIn our examples, we already tried passing variables to methods. However, we haven't differentiated between the different types of variable passing in Java. There are two types of passing data to methods:

• pass-by-value

9.4.3.1 Pass-by-valueWhen a pass-by-value occurs, the method makes a copy of the value of the variable passed to the method. The method cannot accidentally modify the original argument even if it modifies the

Page 8: Java Class Library

parameters during calculations.For example,public class TestPassByValue{

public static void main( String[] args ){int i = 10;//print the value of iSystem.out.println( i );//call method test//and pass i to method testtest( i );//print the value of i. i not changedSystem.out.println( i );}public static void test( int j ){ //change value of parameter j

j = 33;}

}

In the given example, we called the method test and passed the value of i as parameter. The value of i is copied to the variable of the method j. Since j is the variable changed in the test method, it will not affect the variable value if i in main since it is a different copy of the variable.By default, all primitive data types when passed to a method are pass-by-value.

• Pass-byreference9.4.3.2 Pass-by-reference

When a pass-by-reference occurs, the reference to an object is passed to the calling method. This means that, the method makes a copy of the reference of the variable passed to the method. However, unlike in pass-by-value, the method can modify the actual object that the reference is pointing to, since, although different references are used in the methods, the location of the data they are pointing to is the same.

Page 9: Java Class Library

For example,public class TestPassByReference{

public static void main( String[] args ){

//create an array of integersint []ages = {10, 11, 12};//print array valuesfor( int i=0; i<ages.length; i++ ){

System.out.println( ages[i] );}

/* Simulation ages

ages[0] ages[1] ages[2]

i ages.length output 0 3 10 1 11

2 12 */

//call test and pass reference to arraytest( ages );//print array values againfor( int i=0; i<ages.length; i++ ){

System.out.println( ages[i] );}

/* Simulation ages

ages[0] ages[1] ages[2]

i ages.length output 0 3 60 1 61

2 62 */

}public static void test( int[] arr ){ //change values of array

for( int i=0; i<arr.length; i++ ) {

arr[i] = i + 50; } /* Simulation ages

ages[0] ages[1] ages[2] ages[0] ages[1] ages[2]

10 11 12

10 11 12

0 0 0 50 51 52

Page 10: Java Class Library

1st stage 2nd stage i ages.length arr[i]

0 3 arr[0]=0+50 =50 1 arr[1]=1+50 =51

2 arr[2]=2+50 =52

*/ }}

9.4.4 Calling Static MethodsStatic methods are methods that can be invoked without instantiating a class (means without invoking the new keyword). Static methods belongs to the class as a whole and not to a certain instance (or object) of a class. Static methods are distinguished from instance methods in a class definition by the keyword static.

To call a static method, just type,Classname.staticMethodName(params);

• To declare a method as static, place the keyword static before the return type in the method’s declaration.

• You can call any static method by specifying the name of the class in which themethod is declared, followed by a dot (.) and the method name, as in

Page 11: Java Class Library

ClassName.methodName( arguments )

For example, you can calculate the square root of 900.0 with the static method callMath.sqrt( 900.0 )

The preceding expression evaluates to 30.0. Method sqrt takes an argument of type double and returns a result of type double. To output the value of the preceding method call in the command window, you might write the statement

System.out.println( Math.sqrt( 900.0 ) );In this statement, the value that sqrt returns becomes the argument to method println.Note that there was no need to create a Math object before calling method sqrt. Also note that all Math class methods are static—therefore, each is called by preceding the name of the method with the class name Math and the dot (.) separator.

Method arguments may be constants, variables or expressions. If c = 13.0, d = 3.0 and f = 4.0, then the statementSystem.out.println( Math.sqrt( c + d * f ) );calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0—namely, 5.0. Figure 6.2summarizes several Math class methods. In the figure, x and y are of type double

Examples of static methods, we've used so far in our examples are,//prints data to screenSystem.out.println(“Hello world”);

//converts the String 10, to an integerint i = Integer.parseInt(“10”);

//Returns a String representation of the integer argument as an//unsigned integer base 16String hexEquivalent = Integer.toHexString( 10 );

Page 12: Java Class Library

Why Is Method main Declared static?Why must main be declared static? When you execute the Java Virtual Machine (JVM) with the java command, the JVM attempts to invoke the main method of the class you specify—when no objects of the class have been created. Declaring main as static allows the JVM to invoke main without creating an instance of the class. Method main is declared with the header:

public static void main( String args[] )

9.4.5 Scope of a variableIn addition to a variable's data type and name, a variable has scope.

• The scope determines where in the program the variable is accessible. The scope also determines the lifetime of a variable or how long the variable can exist in memory.

• The scope is determined by where the variable declaration is placed in the program.• To simplify things, just think of the scope as anything between the curly braces {...}. • The outer curly braces is called the outer blocks, and the inner curly braces is called

inner blocks.• If you declare variables in the outer block, they are visible (i.e. usable) by the program

lines inside the inner blocks. • However, if you declare variables in the inner block, you cannot expect the outer block to see it.• A variable's scope is inside the block where it is declared, starting from the point where it

is declared, and in the inner blocks.

Page 13: Java Class Library

From Dietel -The basic scope rules are as follows:1. The scope of a parameter declaration is the body of the method in which the declaration appears.2. The scope of a local-variable declaration is from the point at which the declaration appears to the end of that block.3. The scope of a local-variable declaration that appears in the initialization section of a for statement’s header is the body of the for statement and the other expressions in the header.

4. The scope of a method or field of a class is the entire body of the class. This enables non-static methods of a class to use the class’s fields and other methods.

Page 14: Java Class Library

The application in Fig. 6.11 and Fig. 6.12 demonstrates scoping issues with fields and local variables.1 // Fig. 6.11: Scope.java2 // Scope class demonstrates field and local variable scopes.34public class Scope5 {6 // field that is accessible to all methods of this class7 private int x = 1;89 // method begin creates and initializes local variable x10 // and calls methods useLocalVariable and useField11 public void begin()12 {13 int x = 5; // method's local variable x shadows field x14 //If a local variable or parameter in a method has the same name as a field, the field is

// “hidden” until the block terminates execution—this is called shadowing.15 System.out.printf( "local x in method begin is %d\n", x );1617 useLocalVariable(); // useLocalVariable has local x18 useField(); // useField uses class Scope's field x19 useLocalVariable(); // useLocalVariable reinitializes local x20 useField(); // class Scope's field x retains its value2122 System.out.printf( "\nlocal x in method begin is %d\n", x );23 } // end method begin2425 // create and initialize local variable x during each call26 public void useLocalVariable()27 {28 int x = 25; // initialized each time useLocalVariable is called2930 System.out.printf(31 "\nlocal x on entering method useLocalVariable is %d\n", x );32 ++x; // modifies this method's local variable x33 System.out.printf(34 "local x before exiting method useLocalVariable is %d\n", x );35 } // end method useLocalVariable3637 // modify class Scope's field x during each call38 public void useField()39 {40 System.out.printf(41 "\nfield x on entering method useField is %d\n", x );42 x *= 10; // modifies class Scope's field x43 System.out.printf(44 "field x before exiting method useField is %d\n", x );45 } // end method useField46 } // end class Scope

Fig. 6.11 | Scope class demonstrating scopes of a field and local variables.

Page 15: Java Class Library

1 // Fig. 6.12: ScopeTest.java2 // Application to test class Scope.34public class ScopeTest5 {6 // application starting point7 public static void main( String args[] )8 {9 Scope testScope = new Scope();10 testScope.begin();11 } // end main12 } // end class ScopeTest

Outputlocal x in method begin is 5local x on entering method useLocalVariable is 25local x before exiting method useLocalVariable is 26field x on entering method useField is 1field x before exiting method useField is 10local x on entering method useLocalVariable is 25local x before exiting method useLocalVariable is 26field x on entering method useField is 10field x before exiting method useField is 100local x in method begin is 5

Page 16: Java Class Library

9.5 Casting, Converting and Comparing ObjectsIn this section, we are going to learn how to do typecasting. Typecasting or casting is the process of converting a data of a certain data type to another data type. We will also learn how to convert primitive data types to objects and vice versa. And finally, we aregoing to learn how to compare objects.9.5.1 Casting Primitive TypesCasting between primitive types enables you to convert the value of one data from one type to another primitive type. This commonly occurs between numeric types.There is one primitive data type that we cannot do casting though, and that is the boolean data type.

You can explicitly (or purposely) override the unifying type imposed by the Java programming language by performing a type cast. Type casting involves placing the desired result type in parentheses followed by the variable or constant to be cast. For example, two casts are performed in the following code:double bankBalance = 189.66;float weeklyBudget = (float) bankBalance / 4;// weeklyBudget is 47.40, one-fourth of bankBalanceint dollars = (int) weeklyBudget;// dollars is 47, the integer part of weeklyBudget

An example of typecasting is when you want to store an integer data to a variable of data type double. For example,

int numInt = 10;double numDouble = numInt; //implicit cast

In this example, since the destination variable (double) holds a larger value than what we will place inside it, the data is implicitly casted to data type double.

Another example is when we want to typecast an int to a char value or vice versa. A character can be used as an int because each character has a corresponding numeric code that represents its position in the character set. If the variable i has the value 65, the cast (char)i produces the character value 'A'. The numeric code associated with a capital A is 65, according to the ASCII character set, and Java adopted this as part of its character support. For example,

char valChar = 'A';int valInt = valChar;System.out.print( valInt ); //explicit cast: output 65

When we convert a data that has a large type to a smaller type, we must use an explicitcast. Explicit casts take the following form:

(dataType)valuewhere,

dataType, is the name of the data type you're converting tovalue, is an expression that results in the value of the source type.

For example,For example,

double valDouble = 10.12;int valInt = (int)valDouble; //convert valDouble to int type

double x = 10.2;int y = 2;

Page 17: Java Class Library

int result = (int)(x/y); //typecast result of operation toint

9.5.2 Casting Objects (p.145 jedi c.9)Instances of classes also can be cast into instances of other classes, with one restriction: The source and destination classes must be related by inheritance; one class must be a subclass of the other.

The following example casts an instance of the class VicePresident to an instance of the class Employee; VicePresident is a subclass of Employee with more information, which here defines that the VicePresident has executive washroom privileges,

Employee emp = new Employee();VicePresident veep = new VicePresident();emp = veep; // no cast needed for upward useveep = (VicePresident)emp; // must cast explicitlyCasting

9.5.3 Converting Primitive Types to Objects and Vice VersaOne thing you can't do under any circumstance is cast from an object to a primitive data type, or vice versa. Primitive types and objects are very different things in Java, and you can't automatically cast between the two or use them interchangeably.

• As an alternative, the java.lang package includes classes that correspond to each primitive data type: Float, Boolean, Byte, and so on.

• Most of these classes have the same names as the data types, except that the class names begin with a capital letter (Short instead of short, Double instead of double, and the like).

• Also, two classes have names that differ from the corresponding data type: Character is used for char variables and Integer for int variables. (Called Wrapper Classes)

Java treats the data types and their class versions very differently, and a program won't compile successfully if you use one when the other is expected.Using the classes that correspond to each primitive type, you can create an object that holds the same value.

Examples://The following statement creates an instance of the Integer// class with the integer value 7801 (primitive -> Object)Integer dataCount = new Integer(7801);//The following statement converts an Integer object to// its primitive data type int. The result is an int with//value 7801int newCount = dataCount.intValue();

Page 18: Java Class Library

// A common translation you need in programs// is converting a String to a numeric type, such as an int// Object->primitiveString pennsylvania = "65000";int penn = Integer.parseInt(pennsylvania);

9.5.5 Determining the Class of an ObjectWant to find out what an object's class is? Here's the way to do it for an object assignedto the variable key:1. The getClass() method returns a Class object (where Class is itself a class) that hasa method called getName(). In turn, getName() returns a string representing thename of the class.For Example,String name = key.getClass().getName();

Page 19: Java Class Library

Distance Formula: Given the two points (x1, y1) and (x2, y2), the distance between these points is given by the formula:

Java does not include an exponentiation operator, so the designers of Java’s Math class defined static method pow for raising a value to a power.

Ex.

a = p (1 + r)nwherep is the original amount invested (i.e., the principal)r is the annual interest rate (e.g., use 0.05 for 5%)n is the number of yearsa is the amount on deposit at the end of the nth year.

A field width of four characters (as specified by %4d). The amount is output as a floating-point number with the format specifier %,20.2f. The comma (,) formatting flag indicates that the floating-point value should be output with a grouping separator. The actual separator used is specific to the user’s locale (i.e., country). For example, in the United States, the number will be output using commas toseparate every three digits and a decimal point to separate the fractional part of the number, as in 1,234.45. The number 20 in the format specification indicates that the value should be output right justified in a field width of 20 characters. The .2 specifies the formatted number’s precision—in this case, the number is rounded to the nearest hundredth and output with two digits to the right of the decimal point.

Page 20: Java Class Library

Additional Examples

// An application to get the Sum of two numbers illustrating objects, methods and classespublic class Sum{ public void computeSum(int fn, int sn ) { System.out.printf("The sum of %d and %d is %d.",fn,sn,(fn+sn)); } } // end class Sum

---------------------------------------import java.util.Scanner;public class SumTest{ // application starting point public static void main( String args[] ) { Sum mySum = new Sum(); Scanner input=new Scanner(System.in); int firstNumber, secondNumber; System.out.println("Enter the first number: "); firstNumber= input.nextInt(); System.out.println("Enter the first number: "); secondNumber= input.nextInt(); mySum.computeSum(firstNumber, secondNumber); } // end main} // end class SumTest

Page 21: Java Class Library

// Fig. 3.4: GradeBook1.java// Class declaration with a method that has a parameter.

public class GradeBook1{ // display a welcome message to the GradeBook user public void displayMessage(String courseName) { System.out.printf( "Welcome to the grade book for\n%s!\n",courseName ); } // end method displayMessage} // end class GradeBook1

// Fig. 3.5: GradeBookTest1.java// Create GradeBook object and pass a String to// its displayMessage method. import java.util.Scanner; // program uses Scanner

public class GradeBookTest1{ // main method begins program execution public static void main( String args[] ) { // create Scanner to obtain input from command window Scanner input = new Scanner( System.in );

// create a GradeBook1 object and assign it to myGradeBook GradeBook1 myGradeBook = new GradeBook1();

// prompt for and input course name System.out.println( "Please enter the course name:" ); String nameOfCourse = input.nextLine(); // read a line of text System.out.println(); // outputs a blank line

// call myGradeBook's displayMessage method // and pass nameOfCourse as an argument myGradeBook.displayMessage( nameOfCourse ); } // end main} // end class GradeBookTest1

Page 22: Java Class Library

Instance Variables, set Methods and get Methods• Variables declared in the body of a particular method are known as local variables and can be

used only in that method. When that method terminates, the values of its local variables are lost.• A class normally consists of one or more methods that manipulate the attributes that belong to a

particular object of the class. • Attributes are represented as variables in a class declaration. Such variables are called fields

and are declared inside a class declaration but outside the bodies of the class’s method declarations.

• When each object of a class maintains its own copy of an attribute, the field that represents the attribute is also known as an instance variable—each object (instance) of the class has a separate instance of the variable in memory.

Ex. GradeBook Class with an Instance Variable, a set Method and a get Method1 // Fig. 3.7: GradeBook.java2 // GradeBook class that contains a courseName instance variable3 // and methods to set and get its value.45 public class GradeBook6 {7 private String courseName; // course name for this GradeBook89 // method to set the course name10 public void setCourseName( String name )11 {12 courseName = name; // store the course name13 } // end method setCourseName1415 // method to retrieve the course name16 public String getCourseName()17 {18 return courseName;19 } // end method getCourseName2021 / / display a welcome message to the GradeBook user22 public void displayMessage23 {24 // this statement calls getCourseName to get the25 // name of the course this GradeBook represents26 System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName());2728 } // end method displayMessage2930 } // end class GradeBook

Page 23: Java Class Library

1 // Fig. 3.8: GradeBookTest.java2 // Create and manipulate a GradeBook object.3 import java.util.Scanner; // program uses Scanner45 public class GradeBookTest6 {7 // main method begins program execution8 public static void main( String args[] )9 {10 // create Scanner to obtain input from command window11 Scanner input = new Scanner( System.in );1213 // create a GradeBook object and assign it to myGradeBook14 GradeBook myGradeBook = new GradeBook();1516 // display initial value of courseName17 System.out.printf( "Initial course name is: %s\n\n",18 myGradeBook.getCourseName() );1920 // prompt for and read course name21 System.out.println( "Please enter the course name:" );22 String theName = input.nextLine(); // read a line of text23 myGradeBook.setCourseName( theName ); // set the course name24 System.out.println(); // outputs a blank line2526 // display welcome message after specifying course name27 myGradeBook.displayMessage();28 } // end main2930 } // end class GradeBookTest

Note: • Most instance variable declarations are preceded with the keyword private (as in line 7).

Like public, keyword private is an access modifier. Variables or methods declared withaccess modifier private are accessible only to methods of the class in which they are declared.

• Declaring instance variables with access modifier private is known as data hiding. When a program creates (instantiates) an object of class GradeBook, variable courseName is encapsulated (hidden) in the object and can be accessed only by methods of the object’s class.

• Unlike local variables, which are not automatically initialized, every field has a default initial value—a value provided by Java when the programmer does not specify the field’s initial value. Thus, fields are not required to be explicitly initialized before they are used in a program—unless they must be initialized to values other than their default values. The default value for a field of type String (like courseName in this example) is null.

• Reference-type instance variables are initialized by default to the value null—a reserved word that represents a “reference to nothing.”

Page 24: Java Class Library

3.6 Primitive Types vs. Reference Types• Data types in Java are divided into two categories—primitive types and reference types

(sometimes called nonprimitive types). • The primitive types are boolean, byte, char, short, int, long, float and double. All

nonprimitive typ es are reference types, so classes, which specify the types of objects, are reference types.

• A primitive-type variable can store exactly one value of its declared type at a time. For example, an int variable can store one whole number (such as 7) at a time. When another value is assigned to that variable, its initial value is replaced.

• Primitive-type instance variables are initialized by default—variables of types byte, char, short, int, long, float and double are initialized to 0, and variables of type boolean are initialized to false.

• You can specify your own initial values for primitive-type variables.

Compiling an Application with Multiple ClassesEx. javac GradeBook.java GradeBookTest.java

A constructor, which is similar to a method, but is used only at the time an object is created to initialize the object’s data. Ex. Sum mySum= new Sum();

3.7 Initializing Objects with Constructors◦ Each class you declare can provide a constructor that can be used to initialize an object of a

class when the object is created. ◦ In fact, Java requires a constructor call for every object that is created. Keyword new calls

the class’s constructor to perform the initialization. ◦ The constructor call is indicated by the class name followed by parentheses—the

constructor must have the same name as the class.Ex. GradeBook myGradeBook = new GradeBook();

◦ The empty parentheses after “new GradeBook” indicate a call to the class’s constructor without arguments.

◦ By default, the compiler provides a default constructor with no parameters in any class that does not explicitly include a constructor.

◦ When a class has only the default constructor, its instance variables are initialized to their default values. Variables of types char, byte, short, int, long, float and double are initialized to 0, variables of type boolean are initialized to false, and reference-type variables are initialized to null.

◦ When you declare a class, you can provide your own constructor to specify custominitialization for objects of your class. For example, a programmer might want to specify a course name for a GradeBook object when the object is created, as in

GradeBook myGradeBook = new GradeBook( "CS101 Introduction to Java Programming" );• In this case, the argument "CS101 Introduction to Java Programming" is passed to the

GradeBook object’s constructor and used to initialize the courseName. The preceding statementrequires that the class provide a constructor with a String parameter.

Page 25: Java Class Library

1 // Fig. 3.10: GradeBook.java2 // GradeBook class with a constructor to initialize the course name.34 public class GradeBook5 {6 private String courseName; // course name for this GradeBook78 // constructor initializes courseName with String supplied as argument9 public GradeBook( String name )10 {11 courseName = name; // initializes courseName12 } // end constructor1314 // method to set the course name15 public void setCourseName( String name )16 {17 courseName = name; // store the course name18 } // end method setCourseName1920 // method to retrieve the course name21 public String getCourseName()22 {23 return courseName;24 } // end method getCourseName2526 // display a welcome message to the GradeBook user27 public void displayMessage()28 {29 // this statement calls getCourseName to get the30 // name of the course this GradeBook represents31 System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() );32 33 } // end method displayMessage3435 } // end class GradeBook

Fig. 3.10 | GradeBook class with a constructor to initialize the course name.

• Lines 9–12 declare the constructor for class GradeBook. A constructor must have thesame name as its class. Like a method, a constructor specifies in its parameter list the datait requires to perform its task.

• Like methods, constructors also can take arguments. However, an important differencebetween constructors and methods is that constructors cannot return values, so they cannot specify a return type (not even void). Normally, constructors are declared public. If a class does not include a constructor, the class’s instance variables are initialized to their default values. If a programmer declares any constructors for a class, the Java compiler will not create a default constructor for that class.

Page 26: Java Class Library

1 // Fig. 3.11: GradeBookTest.java2 // GradeBook constructor used to specify the course name at the3 // time each GradeBook object is created.45 public class GradeBookTest6 {7 // main method begins program execution8 public static void main( String args[] )9 {10 // create GradeBook object11 GradeBook gradeBook1 = new GradeBook(12 "CS101 Introduction to Java Programming" );13 GradeBook gradeBook2 = new GradeBook(14 "CS102 Data Structures in Java" );15 16 // display initial value of courseName for each GradeBook17 System.out.printf( "gradeBook1 course name is: %s\n",18 gradeBook1.getCourseName() );19 System.out.printf( "gradeBook2 course name is: %s\n",20 gradeBook2.getCourseName() );21 } // end main2223 } // end class GradeBookTest

Output gradeBook1 course name is: CS101 Introduction to Java ProgramminggradeBook2 course name is: CS102 Data Structures in Java

Fig. 3.11 | GradeBook constructor used to specify the course name at the time eachGradeBook object is created.

Page 27: Java Class Library

ASSIGNMENT:

3.13 Create a class called Invoice that a hardware store might use to represent an invoice for an item sold at the store. An Invoice should include four pieces of information as instance variables—a part number (type String), a part description (type String), a quantity of the item being purchased(type int) and a price per item (double). Your class should have a constructor that initializes the four instance variables. Provide a set and a get method for each instance variable. In addition, provide a method named getInvoiceAmount that calculates the invoice amount (i.e., multiplies the quantity by the price per item), then returns the amount as a double value. If the quantity is not positive, it should be set to 0. If the price per item is not positive, it should be set to 0.0. Write a test application named InvoiceTest that demonstrates class Invoice’s capabilities.

3.14 Create a class called Employee that includes three pieces of information as instance variables— a first name (type String), a last name (type String) and a monthly salary (double). Your class should have a constructor that initializes the three instance variables. Provide a set and a get method for each instance variable. If the monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then give each Employee a 10% raise and display each Employee’s yearly salary again.

3.15 Create a class called Date that includes three pieces of information as instance variables—amonth (type int), a day (type int) and a year (type int). Your class should have a constructor thatinitializes the three instance variables and assumes that the values provided are correct. Provide a setand a get method for each instance variable. Provide a method displayDate that displays the month,day and year separated by forward slashes (/). Write a test application named DateTest that demonstrates class Date’s capabilities.