Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
Workshop: Lab 3                                                                                                           Engineering Software 1 
Lab 3: 
Introduction to Classes and Objects 
 
Learning Objectives 
 
In this lab exercise you will learn: 
1. What classes, objects, methods and instance variables are.  
2. How to declare a class and use it to create an object.  
3. How to declare methods in a class to implement the class's behaviors.  
4. How to declare instance variables in a class to implement the class's attributes.  
5. How to call an object's method to make that method perform its task.  
6. The differences between instance variables of a class and local variables of a 
method.  
7. How to use a constructor to ensure that an object's data is initialized when the 
object is created.  
8. The differences between primitive and reference types.  
 
 
Lab Work 
General Note: Study every exercise and for each of them draw a structure diagram. Type 
in all these programs and run them inside your Java development kit.  
In your log-book take note of all the results from the execution of these programs and 
write down any problems that you had to solve. 
For each program of the exercises, explain clearly what each section of the program is 
doing. You may need to perform a walk-through, line by line, where this is appropriate. 
Record all your explanations in the log-book. 
Remember to put a date in your log-book and also to offer some discussions and a brief 
conclusion after every week’s work. 
Finally, complete the programming assignments at the end of the exercises, then enter 
comments in your logbook as you are doing this and save to your floppy disk/CD for 
submission with your logbook. 
 
Background 
• Performing a task in a program requires a method. Inside the method you put the mechanisms that 
make the method do its tasks—that is, the method hides the implementation details of the tasks that 
it performs.  
• The program unit that houses a method is called a class. A class may contain one or more methods 
that are designed to perform the class's tasks.  
• A method can perform a task and return a result.  
• A class can be used to create an instance of the class called an object. This is one of the reasons 
Java is known as an object-oriented programming language.  
• Each message sent to an object is known as a method call and tells a method of the object to 
perform its task.  
• Each method can specify parameters that represent additional information the method requires to 
perform its task correctly. A method call supplies values—called arguments—for the method's 
parameters.  
Stavros Dimitriou                                   ©London South Bank University 1
Workshop: Lab 3                                                                                                           Engineering Software 1 
• An object has attributes that are carried with the object as it is used in a program. These attributes 
are specified as part of the object's class. Attributes are specified in classes by fields.  
• Each class declaration that begins with keyword public must be stored in a file that has exactly the 
same name as the class and ends with the .java file-name extension.  
• Keyword public is an access modifier.  
• Every class declaration contains keyword class followed immediately by the class's name.  
• A method declaration that begins with keyword public indicates that the method is "available to 
the public"—that is, it can be called by other classes declared outside the class declaration.  
• Keyword void indicates that a method will perform a task but will not return any information when 
it completes its task.  
• By convention, method names begin with a lowercase first letter and all subsequent words in the 
name begin with a capital first letter.  
• Empty parentheses following a method name indicate that the method does not require any 
parameters to perform its task.  
• Every method's body is delimited by left and right braces ({ and }).  
• The body of a method contains statements that perform the method's task. After the statements 
execute, the method has completed its task.  
• When you attempt to execute a class, Java looks for the class's main method to begin execution.  
• Any class that contains public static void main( String args[] ) can be used to execute an 
application.  
• Typically, you cannot call a method that belongs to another class until you create an object of that 
class.  
• Class instance creation expressions beginning with keyword new create new objects.  
• To call a method of an object, follow the variable name with a dot separator (.), the method name 
and a set of parentheses containing the method's arguments.  
• Methods often require additional information to perform their tasks. Such additional information is 
provided to methods via arguments in method calls.  
• Scanner method nextLine reads characters until a newline character is encountered, then returns 
the characters as a String.  
• Scanner method next reads characters until any white-space character is encountered, then returns 
the characters as a String.  
• A method that requires data to perform its task must specify this in its declaration by placing 
additional information in the method's parameter list.  
• Each parameter must specify both a type and an identifier.  
• At the time a method is called, its arguments are assigned to its parameters. Then the method body 
uses the parameter variables to access the argument values.  
• A method can specify multiple parameters by separating each parameter from the next with a 
comma.  
• The number of arguments in the method call must match the number of parameters in the method 
declaration's parameter list. Also, the argument types in the method call must be consistent with 
the types of the corresponding parameters in the method's declaration.  
• Class String is in package java.lang, which is imported implicitly into all source-code files.  
• There is a special relationship between classes that are compiled in the same directory on disk. By 
default, such classes are considered to be in the same package—known as the default package. 
Classes in the same package are implicitly imported into the source code files of other classes in 
the same package. Thus, an import declaration is not required when one class in a package uses 
another in the same package.  
• An import declaration is not required if you always refer to a class with its fully qualified class 
name.  
• Variables declared in the body of a particular method are known as local variables and can be used 
only in that method.  
• A class normally consists of one or more methods that manipulate the attributes (data) that belong 
to a particular object of the class. Attributes are represented as fields 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.  
Stavros Dimitriou                                   ©London South Bank University 2
Workshop: Lab 3                                                                                                           Engineering Software 1 
• Most instance variable declarations are preceded with the private 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.  
• A benefit of fields is that all the methods of the class can use the fields. Another distinction 
between a field and a local variable is that a field has a default initial value provided by Java when 
the programmer does not specify the field's initial value, but a local variable does not.  
• The default value for a field of type String is null.  
• When a method that specifies a return type is called and completes its task, the method returns a 
result to its calling method.  
• Classes often provide public methods to allow clients of the class to set or get private instance 
variables. The names of these methods need not begin with set or get, but this naming convention 
is highly recommended in Java and is required for special Java software components called 
JavaBeans.  
• 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 other types 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.  
• Primitive-type instance variables are initialized by default. Variables of types byte, char, short, int, 
long, float and double are initialized to 0. Variables of type boolean are initialized to false.  
• Programs use variables of reference types (called references) to store the location of an object in 
the computer's memory. Such variables refer to objects in the program. The object that is 
referenced may contain many instance variables and methods.  
• Reference-type fields are initialized by default to the value null.  
• A reference to an object is required to invoke an object's instance methods. A primitive-type 
variable does not refer to an object and therefore cannot be used to invoke a method.  
• A constructor can be used to initialize an object of a class when the object is created.  
• Constructors can specify parameters but cannot specify return types.  
• If no constructor is provided for a class, the compiler provides a default constructor with no 
parameters.  
• A floating-point number is a number with a decimal point, such as 7.33, 0.0975 or 1000.12345. 
Java provides two primitive types for storing floating-point numbers in memory—float and double. 
The primary difference between these types is that double variables can store numbers with larger 
magnitude and finer detail (known as the number's precision) than float variables.  
• Variables of type float represent single-precision floating-point numbers and have seven 
significant digits. Variables of type double represent double-precision floating-point numbers. 
These require twice as much memory as float variables and provide 15 significant digits—
approximately double the precision of float variables.  
• Floating-point values that appear in source code are known as floating-point literals and are type 
double by default.  
• Scanner method nextDouble returns a double value.  
• The format specifier %f is used to output values of type float or double. A precision can be 
specified between % and f to represent the number of decimal places that should be output to the 
right of the decimal point in the floating-point number.  
• The default value for a field of type double is 0.0, and the default value for a field of type int is 0.  
 
 
 
 
 
 
 
Stavros Dimitriou                                   ©London South Bank University 3
Workshop: Lab 3                                                                                                           Engineering Software 1 
Part A: Reinforce your understanding of key Java programming concepts 
 
After reading the background above along with lecture notes, answer the given questions. 
The questions are intended to test and reinforce your understanding of key concepts. 
 
For each term in the left column, write the letter for the description from the right column 
that best matches the term. 
 
 
 
Answer the following questions in your logbook. Your answers should be as concise as 
possible; aim for two or three sentences. 
 
1. List the parts of a method header and explain why each one is important. 
2. How are constructors and methods similar? How are they different? 
3. What is the relationship between a client of an object and the object’s public 
members? 
4. What types of declarations are contained within a class declaration? 
5. Distinguish between a primitive-type variable and a reference-type variable. 
 
Stavros Dimitriou                                   ©London South Bank University 4
Workshop: Lab 3                                                                                                           Engineering Software 1 
Part B: Java programs 
 
Exercise 1: Declaring a Class with a Method and Instantiating an Object of a Class 
We begin with an example that consists of classes GradeBook (Program 1) and 
GradeBookTest (Program 2). Class GradeBook (declared in file GradeBook.java) will be 
used to display a message on the screen (Program 2) welcoming the instructor to the 
grade-book application. Class GradeBookTest (declared in file GradeBookTest.java) is an 
application class in which the main method will use class GradeBook. 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. Thus, classes GradeBook 
and GradeBookTest must be declared in separate files, because each class is declared 
public. 
 
1. Analyze the structure of the following two Java programs. 
2. Understand the program and predict the outcome in your logbook. 
 __________________________________________________________ 
 
 // Program 1: GradeBook.java 
// Class declaration with one method. 
 
public class GradeBook 
{ 
   // display a welcome message to the GradeBook user 
   public void displayMessage() 
   { 
      System.out.println( "Welcome to the Grade Book!" ); 
   } // end method displayMessage 
 
} // end class GradeBook 
__________________________________________________________ 
 
// Program 2: GradeBookTest.java 
// Create a GradeBook object and call its displayMessage method. 
 
public class GradeBookTest 
{ 
   // main method begins program execution 
   public static void main( String args[] ) 
   {  
      // create a GradeBook object and assign it to myGradeBook 
      GradeBook myGradeBook = new GradeBook();  
 
      // call myGradeBook's displayMessage method 
      myGradeBook.displayMessage();  
   } // end main 
 
} // end class GradeBookTest 
__________________________________________________________ 
 
3. Create, Compile and Run the program.  
 
 
Exercise2: Instance Variables, set Methods and get Methods 
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 
Stavros Dimitriou                                   ©London South Bank University 5
Workshop: Lab 3                                                                                                           Engineering Software 1 
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. The example in this section demonstrates a GradeBook class that 
contains a courseName instance variable to represent a particular GradeBook object’s 
course name. 
 
1. Analyze the structure of the following two Java programs. 
2. Understand the program and predict the outcome in your logbook. 
 __________________________________________________________ 
 
// GradeBook.java 
// GradeBook class that contains a courseName instance variable  
// and methods to set and get its value. 
 
public class GradeBook 
{ 
   private String courseName; // course name for this GradeBook 
 
   // method to set the course name 
   public void setCourseName( String name ) 
   { 
      courseName = name; // store the course name 
   } // end method setCourseName 
 
   // method to retrieve the course name 
   public String getCourseName() 
   { 
      return courseName; 
   } // end method getCourseName 
 
   // display a welcome message to the GradeBook user 
   public void displayMessage() 
   { 
      // this statement calls getCourseName to get the  
      // name of the course this GradeBook represents 
      System.out.printf( "Welcome to the grade book for\n%s!\n",  
         getCourseName() ); 
   } // end method displayMessage 
 
} // end class GradeBook 
__________________________________________________________ 
 
// GradeBookTest.java 
// Create and manipulate a GradeBook object. 
import java.util.Scanner; // program uses Scanner 
 
public class GradeBookTest 
{ 
   // 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 GradeBook object and assign it to myGradeBook 
      GradeBook myGradeBook = new GradeBook();  
 
      // display initial value of courseName 
      System.out.printf( "Initial course name is: %s\n\n", 
         myGradeBook.getCourseName() ); 
 
Stavros Dimitriou                                   ©London South Bank University 6
Workshop: Lab 3                                                                                                           Engineering Software 1 
      // prompt for and read course name 
      System.out.println( "Please enter the course name:" ); 
      String theName = input.nextLine(); // read a line of text 
      myGradeBook.setCourseName( theName ); // set the course name 
      System.out.println(); // outputs a blank line 
 
      // display welcome message after specifying course name 
      myGradeBook.displayMessage(); 
   } // end main 
 
} // end class GradeBookTest 
__________________________________________________________ 
 
3. Create, Compile and Run the program.  
 
Exercise 3: 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. 
 
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" );
 
1. Analyze the structure of the following two Java programs. 
2. Understand the program and predict the outcome in your logbook. 
 __________________________________________________________ 
 
 // GradeBook.java 
// GradeBook class with a constructor to initialize the course name. 
 
public class GradeBook 
{ 
   private String courseName; // course name for this GradeBook 
 
   // constructor initializes courseName with String supplied as argument 
   public GradeBook( String name ) 
   { 
      courseName = name; // initializes courseName 
   } // end constructor 
 
   // method to set the course name 
   public void setCourseName( String name ) 
   { 
      courseName = name; // store the course name 
   } // end method setCourseName 
 
   // method to retrieve the course name 
   public String getCourseName() 
   { 
      return courseName; 
   } // end method getCourseName 
 
   // display a welcome message to the GradeBook user 
   public void displayMessage() 
   { 
Stavros Dimitriou                                   ©London South Bank University 7
Workshop: Lab 3                                                                                                           Engineering Software 1 
      // this statement calls getCourseName to get the  
      // name of the course this GradeBook represents 
      System.out.printf( "Welcome to the grade book for\n%s!\n",  
         getCourseName() ); 
   } // end method displayMessage 
 
} // end class GradeBook 
__________________________________________________________ 
 
// GradeBookTest.java 
// GradeBook constructor used to specify the course name at the  
// time each GradeBook object is created. 
 
public class GradeBookTest 
{ 
   // main method begins program execution 
   public static void main( String args[] ) 
   {  
      // create GradeBook object 
      GradeBook gradeBook1 = new GradeBook(  
         "CS101 Introduction to Java Programming" );  
      GradeBook gradeBook2 = new GradeBook(  
         "CS102 Data Structures in Java" ); 
 
      // display initial value of courseName for each GradeBook 
      System.out.printf( "gradeBook1 course name is: %s\n", 
         gradeBook1.getCourseName() ); 
      System.out.printf( "gradeBook2 course name is: %s\n", 
         gradeBook2.getCourseName() ); 
   } // end main 
 
} // end class GradeBookTest 
__________________________________________________________ 
 
3. Create, Compile and Run the program.  
 
Exercise 4 
For each of the given program segments, read the code, and write the output in your 
logbook. 
 
5.1 What is output by the following main method? 
 
 
 
 
5.2 What is output by the following main method? 
 
 
Stavros Dimitriou                                   ©London South Bank University 8
Workshop: Lab 3                                                                                                           Engineering Software 1 
Programming Assignment 
  
1. Explain the following programs and predict the outputs in your logbook. 
 __________________________________________________________ 
 
 // Account.java 
// Account class with a constructor to  
// initialize instance variable balance. 
 
public class Account 
{    
   private double balance; // instance variable that stores the balance 
 
   // constructor   
   public Account( double initialBalance ) 
   { 
      // validate that initialBalance is greater than 0.0;  
      // if it is not, balance is initialized to the default value 0.0 
      if ( initialBalance > 0.0 )  
         balance = initialBalance;  
   } // end Account constructor 
 
   // credit (add) an amount to the account 
   public void credit( double amount ) 
   {       
      balance = balance + amount; // add amount to balance  
   } // end method credit 
 
   // return the account balance 
   public double getBalance() 
   { 
      return balance; // gives the value of balance to the calling method 
   } // end method getBalance 
 
} // end class Account 
__________________________________________________________ 
 
// AccountTest.java 
// Create and manipulate an Account object. 
import java.util.Scanner; 
 
public class AccountTest 
{ 
   // main method begins execution of Java application 
   public static void main( String args[] )  
   { 
      Account account1 = new Account( 50.00 ); // create Account object 
      Account account2 = new Account( -7.53 ); // create Account object 
 
      // 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() ); 
       
      // create Scanner to obtain input from command window 
      Scanner input = new Scanner( System.in ); 
      double depositAmount; // deposit amount read from user 
 
      System.out.print( "Enter deposit amount for account1: " ); // 
prompt 
      depositAmount = input.nextDouble(); // obtain user input 
      System.out.printf( "\nadding %.2f to account1 balance\n\n",  
         depositAmount ); 
      account1.credit( depositAmount ); // add to account1 balance 
Stavros Dimitriou                                   ©London South Bank University 9
Workshop: Lab 3                                                                                                           Engineering Software 1 
 
      // display balances 
      System.out.printf( "account1 balance: $%.2f\n",  
         account1.getBalance() ); 
      System.out.printf( "account2 balance: $%.2f\n\n",  
         account2.getBalance() ); 
 
      System.out.print( "Enter deposit amount for account2: " ); // 
prompt 
      depositAmount = input.nextDouble(); // obtain user input 
      System.out.printf( "\nadding %.2f to account2 balance\n\n",  
         depositAmount ); 
      account2.credit( depositAmount ); // add to account2 balance 
 
      // display balances 
      System.out.printf( "account1 balance: $%.2f\n",  
         account1.getBalance() ); 
      System.out.printf( "account2 balance: $%.2f\n",  
         account2.getBalance() ); 
   } // end main 
 
} // end class AccountTest 
__________________________________________________________ 
 
Stavros Dimitriou                                   ©London South Bank University 10