Sei sulla pagina 1di 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.

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.java 2 // Class declaration with one method. 3 4 public class GradeBook 5 { 6 // display a welcome message to the GradeBook user 7 public void displayMessage() 8 { 9 System.out.println( "Welcome to the Grade Book!" ); 10 } // end method displayMessage 11 12 } // end class GradeBook Fig. 3.1 | Class declaration with one method. ------------------------------------------------------1 // Fig. 3.2: GradeBookTest.java 2 // Create a GradeBook object and call its displayMessage method. 3 4 public class GradeBookTest 5{ 6 // main method begins program execution 7 public static void main( String args[] ) 8 { 9 // create a GradeBook object and assign it to myGradeBook 10 GradeBook myGradeBook = new GradeBook(); 11 12 // call myGradeBook's displayMessage method 13 myGradeBook.displayMessage(); 14 } // end main 15 16 } // end class GradeBookTest Output:
Welcome to the Grade Book!

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 over and over again to create many objects.

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 Instantiation To 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[]) {

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 Methods 9.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 other method 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 are also 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 can do 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.java 2 // Class declaration with a method that has a parameter. 3 4public class GradeBook 5{ 6 // display a welcome message to the GradeBook user 7 public void displayMessage( ) 8 { 9 System.out.printf( "Welcome to the grade book for\n%s!\n", 10 courseName );11 12 } // end method displayMessage

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

1 // Fig. 3.5: GradeBookTest.java 2 // Create GradeBook object and pass a String to 3 // its displayMessage method. 4 import java.util.Scanner; // program uses Scanner 5 6 public class GradeBookTest 7{ 8 // main method begins program execution 9 public static void main( String args[] ) 10 { 11 // create Scanner to obtain input from command window 12 Scanner input = new Scanner( System.in ); 13 14 // create a GradeBook object and assign it to myGradeBook 15 GradeBook myGradeBook = new GradeBook(); 16 17 // prompt for and input course name 18 System.out.println( "Please enter the course name:" ); 19 String nameOfCourse = input.nextLine(); // read a line of text 20 System.out.println(); // outputs a blank line 21 22 // call myGradeBook's displayMessage method 23 // and pass nameOfCourse as an argument 24 myGradeBook.displayMessage( nameOfCourse ); 25 } // end main 26 27 } // 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 Programming Welcome to the grade book for CS101 Introduction to Java Programming! ------------------Line 24 calls myGradeBookss 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 displayMessages parameter courseName in line 7 of Fig. 3.4. When you execute this application, notice that method displayMessage outputs the name you type as part of the welcome message (Fig. 3.5). Method nextLine reads characters typed by the user until the newline character is encountered, then returns

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 valuescalled argumentsfor each of the methods 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 Methods In 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-value When 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

parameters during calculations. For example, public class TestPassByValue { public static void main( String[] args ) { int i = 10; //print the value of i System.out.println( i ); //call method test //and pass i to method test test( i ); //print the value of i. i not changed System.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-byreference 9.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.

For example, public class TestPassByReference { public static void main( String[] args ) { //create an array of integers int []ages = {10, 11, 12}; //print array values for( int i=0; i<ages.length; i++ ) { System.out.println( ages[i] ); } /* Simulation 11 12 ages10 ages[0] ages[1] ages[2] i ages.length 0 3 1 output 10 11 12

2 */ //call test and pass reference to array test( ages ); //print array values again for( int i=0; i<ages.length; i++ ) { System.out.println( ages[i] ); } /* Simulation 11 12 ages10 ages[0] ages[1] ages[2] i 2 */ ages.length 0 3 1 output 60 61 62

} public static void test( int[] arr ) { //change values of array for( int i=0; i<arr.length; i++ ) { arr[i] = i + 50; } /* Simulation 0 0 ages 0 ages[0] ages[1] ages[2]

50

51

52

ages[0]

ages[1] ages[2]

1st 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 */ } }

2nd stage

9.4.4 Calling Static Methods Static 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 methods declaration. You can call any static method by specifying the name of the class in which the method is declared, followed by a dot (.) and the method name, as in

ClassName.methodName( arguments ) For example, you can calculate the square root of 900.0 with the static method call Math.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 statictherefore, 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 statement System.out.println( Math.sqrt( c + d * f ) ); calculates and prints the square root of 13.0 + 3.0 * 4.0 = 25.0namely, 5.0. Figure 6.2 summarizes 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 screen System.out.println(Hello world); //converts the String 10, to an integer int i = Integer.parseInt(10); //Returns a String representation of the integer argument as an //unsigned integer base 16 String hexEquivalent = Integer.toHexString( 10 );

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 specifywhen 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 variable In 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.

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 statements 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 classs fields and other methods.

The application in Fig. 6.11 and Fig. 6.12 demonstrates scoping issues with fields and local variables. 1 // Fig. 6.11: Scope.java 2 // Scope class demonstrates field and local variable scopes. 3 4public class Scope 5{ 6 // field that is accessible to all methods of this class 7 private int x = 1; 8 9 // method begin creates and initializes local variable x 10 // and calls methods useLocalVariable and useField 11 public void begin() 12 { 13 int x = 5; // method's local variable x shadows field x 14 //If a local variable or parameter in a method has the same name as a field, the field is // hidden until the block terminates executionthis is called shadowing. 15 System.out.printf( "local x in method begin is %d\n", x ); 16 17 useLocalVariable(); // useLocalVariable has local x 18 useField(); // useField uses class Scope's field x 19 useLocalVariable(); // useLocalVariable reinitializes local x 20 useField(); // class Scope's field x retains its value 21 22 System.out.printf( "\nlocal x in method begin is %d\n", x ); 23 } // end method begin 24 25 // create and initialize local variable x during each call 26 public void useLocalVariable() 27 { 28 int x = 25; // initialized each time useLocalVariable is called 29 30 System.out.printf( 31 "\nlocal x on entering method useLocalVariable is %d\n", x ); 32 ++x; // modifies this method's local variable x 33 System.out.printf( 34 "local x before exiting method useLocalVariable is %d\n", x ); 35 } // end method useLocalVariable 36 37 // modify class Scope's field x during each call 38 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 x 43 System.out.printf( 44 "field x before exiting method useField is %d\n", x ); 45 } // end method useField 46 } // end class Scope Fig. 6.11 | Scope class demonstrating scopes of a field and local variables.

1 // Fig. 6.12: ScopeTest.java 2 // Application to test class Scope. 3 4public class ScopeTest 5{ 6 // application starting point 7 public static void main( String args[] ) 8 { 9 Scope testScope = new Scope(); 10 testScope.begin(); 11 } // end main 12 } // end class ScopeTest Output local x in method begin is 5 local x on entering method useLocalVariable is 25 local x before exiting method useLocalVariable is 26 field x on entering method useField is 1 field x before exiting method useField is 10 local x on entering method useLocalVariable is 25 local x before exiting method useLocalVariable is 26 field x on entering method useField is 10 field x before exiting method useField is 100 local x in method begin is 5

9.5 Casting, Converting and Comparing Objects In 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 are going to learn how to compare objects. 9.5.1 Casting Primitive Types Casting 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 bankBalance int 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 explicit cast. Explicit casts take the following form: (dataType)value where, dataType, is the name of the data type you're converting to value, 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;

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

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 use veep = (VicePresident)emp; // must cast explicitlyCasting

9.5.3 Converting Primitive Types to Objects and Vice Versa One 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 7801 int newCount = dataCount.intValue();

// A common translation you need in programs // is converting a String to a numeric type, such as an int // Object->primitive String pennsylvania = "65000"; int penn = Integer.parseInt(pennsylvania); 9.5.5 Determining the Class of an Object Want to find out what an object's class is? Here's the way to do it for an object assigned to the variable key: 1. The getClass() method returns a Class object (where Class is itself a class) that has a method called getName(). In turn, getName() returns a string representing the name of the class. For Example, String name = key.getClass().getName();

Distance Formula: Given the two points the formula:

(x1, y1) and (x2, y2), the distance between these points is given by

Java does not include an exponentiation operator, so the designers of Javas Math class defined static method pow for raising a value to a power. Ex. a = p (1 + r)n where p 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 years a 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 users locale (i.e., country). For example, in the United States, the number will be output using commas to separate 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 numbers precisionin this case, the number is rounded to the nearest hundredth and output with two digits to the right of the decimal point.

Additional Examples // An application to get the Sum of two numbers illustrating objects, methods and classes public 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

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

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 classs 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 variableeach 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 Method 1 // Fig. 3.7: GradeBook.java 2 // GradeBook class that contains a courseName instance variable 3 // and methods to set and get its value. 4 5 public class GradeBook 6{ 7 private String courseName; // course name for this GradeBook 8 9 // method to set the course name 10 public void setCourseName( String name ) 11 { 12 courseName = name; // store the course name 13 } // end method setCourseName 14 15 // method to retrieve the course name 16 public String getCourseName() 17 { 18 return courseName; 19 } // end method getCourseName 20 21 / / display a welcome message to the GradeBook user 22 public void displayMessage 23 { 24 // this statement calls getCourseName to get the 25 // name of the course this GradeBook represents 26 System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName()); 27 28 } // end method displayMessage 29 30 } // end class GradeBook

1 // Fig. 3.8: GradeBookTest.java 2 // Create and manipulate a GradeBook object. 3 import java.util.Scanner; // program uses Scanner 4 5 public class GradeBookTest 6{ 7 // main method begins program execution 8 public static void main( String args[] ) 9 { 10 // create Scanner to obtain input from command window 11 Scanner input = new Scanner( System.in ); 12 13 // create a GradeBook object and assign it to myGradeBook 14 GradeBook myGradeBook = new GradeBook(); 15 16 // display initial value of courseName 17 System.out.printf( "Initial course name is: %s\n\n", 18 myGradeBook.getCourseName() ); 19 20 // prompt for and read course name 21 System.out.println( "Please enter the course name:" ); 22 String theName = input.nextLine(); // read a line of text 23 myGradeBook.setCourseName( theName ); // set the course name 24 System.out.println(); // outputs a blank line 25 26 // display welcome message after specifying course name 27 myGradeBook.displayMessage(); 28 } // end main 29 30 } // 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 with access 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 objects class. Unlike local variables, which are not automatically initialized, every field has a default initial valuea value provided by Java when the programmer does not specify the fields 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 nulla reserved word that represents a reference to nothing.

3.6 Primitive Types vs. Reference Types Data types in Java are divided into two categoriesprimitive 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 defaultvariables 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 Classes Ex. 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 objects 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 classs constructor to perform the initialization. The constructor call is indicated by the class name followed by parenthesesthe 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 classs 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 custom initialization 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 objects constructor and used to initialize the courseName. The preceding statement requires that the class provide a constructor with a String parameter.

1 // Fig. 3.10: GradeBook.java 2 // GradeBook class with a constructor to initialize the course name. 3 4 public class GradeBook 5{ 6 private String courseName; // course name for this GradeBook 7 8 // constructor initializes courseName with String supplied as argument 9 public GradeBook( String name ) 10 { 11 courseName = name; // initializes courseName 12 } // end constructor 13 14 // method to set the course name 15 public void setCourseName( String name ) 16 { 17 courseName = name; // store the course name 18 } // end method setCourseName 19 20 // method to retrieve the course name 21 public String getCourseName() 22 { 23 return courseName; 24 } // end method getCourseName 25 26 // display a welcome message to the GradeBook user 27 public void displayMessage() 28 { 29 // this statement calls getCourseName to get the 30 // name of the course this GradeBook represents 31 System.out.printf( "Welcome to the grade book for\n%s!\n", getCourseName() ); 32 33 } // end method displayMessage 34 35 } // end class GradeBook Fig. 3.10 | GradeBook class with a constructor to initialize the course name. Lines 912 declare the constructor for class GradeBook. A constructor must have the same name as its class. Like a method, a constructor specifies in its parameter list the data it requires to perform its task. Like methods, constructors also can take arguments. However, an important difference between 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 classs 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.

1 // Fig. 3.11: GradeBookTest.java 2 // GradeBook constructor used to specify the course name at the 3 // time each GradeBook object is created. 4 5 public class GradeBookTest 6{ 7 // main method begins program execution 8 public static void main( String args[] ) 9 { 10 // create GradeBook object 11 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 GradeBook 17 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 main 22 23 } // end class GradeBookTest Output gradeBook1 course name is: CS101 Introduction to Java Programming gradeBook2 course name is: CS102 Data Structures in Java Fig. 3.11 | GradeBook constructor used to specify the course name at the time each GradeBook object is created.

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 Invoices 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 Employees capabilities. Create two Employee objects and display each objects yearly salary. Then give each Employee a 10% raise and display each Employees yearly salary again. 3.15 Create a class called Date that includes three pieces of information as instance variablesa month (type int), a day (type int) and a year (type int). Your class should have a constructor that initializes the three instance variables and assumes that the values provided are correct. Provide a set and 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 Dates capabilities.

Potrebbero piacerti anche