Java Classes
Download
Report
Transcript Java Classes
Java Classes
Java Classes
• Consider this simplistic class
Specified public
public class ProjInfo
{ProjInfo()
{System.out.println("This program computes factorial of number");
System.out.println("passed via command line at a DOS prompt");
System.out.println("Syntax for command line
It's is
task");
is to print
System.out.print("C:\\Jview Prog1 <integer>\n\n");
information or directions
System.out.print("Example:
C:\\PROG1 6\n\n");
for the user
System.out.print("Program computes, displays 720 which is 6!");
}
}
This class has exactly one
function, the constructor
Java Classes
• Calling the class
import ProjInfo;
ClassAispointer
imported
to a class
object is declared
(but no class object
is yet instantiated)
public class Class1
{public ProjInfo intro;
public static void main (String[] args)
{
int count = 1, entered = 1, result = 1;
ProjInfo intro = new ProjInfo();
if (args.length ==1)
• new is used to instantiate
count = entered = Integer.parseInt(args[0],10);
and initialize a class object
else
{ . . .
• The constructor is called and
executes the sequence of
printline commands
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// Fig. 8.1: Time1.java
// Time1 class definition
import java.text.DecimalFormat;
//
// This class maintains the time in
public class Time1 extends Object {
private int hour;
// 0 - 23
private int minute;
// 0 - 59
private int second;
// 0 - 59
Name of file and name of
must formatting
be same …
used class
for number
including case of
24-hour format
characters
Time
Class
Each file needs exactly one public
class, which is the filename.
Time1 inherits from class Object.
// Time1 constructor initializes each instance variable
// to zero. Ensures that each Time1 object starts in a
private instance
// consistent state.
variables can only be
public Time1()
accessed by methods
{
setTime( 0, 0, 0 );
in theirTime1
class.constructor,
}
initializes new Time1
objects.
// Set a new time value using universal time. Perform
// validity checks on the data. Set invalid values to zero.
public void setTime( int h, int m, int s )
{
hour = ( ( h >= 0 && h < 24 ) ? h : 0 );
public method, may
minute = ( ( m >= 0 && m < 60 ) ? m : 0 );
accessed through a
second = ( ( s >= 0 && s < 60 ) ? s : 0 );
}
Time1 reference.
Checks validity of
arguments.
be
28
// Convert to String in universal-time format
29
public String toUniversalString()
30
{
31
DecimalFormat twoDigits = new DecimalFormat( "00" );
32
33
return twoDigits.format( hour ) + ":" +
34
twoDigits.format( minute ) + ":" +
35
twoDigits.format( second );
36
Time
Class
}
37
38
// Convert to String in standard-time
39
public String toString()
40
{
41
Method toString implicitly
knows to use instance
variables of the object that
format invoked it.
DecimalFormat twoDigits = new DecimalFormat( "00" );
42
43
return ( (hour == 12 || hour == 0) ? 12 : hour % 12 ) +
44
":" + twoDigits.format( minute ) +
45
":" + twoDigits.format( second ) +
46
( hour < 12 ? " AM" : " PM" );
47
48 }
}
What other
differences and
similarities with
C++ classes do
you see?
Classes as Extensions
class Account {
String name;
String address;
int accountNumber;
void displayNameAndAddress() {
Note the name of System.out.println(name);
System.out.println(address);
this class
}
Given the class
on the left:
Where is this
defined?
public static void main(String args[]) {
Saving billsSavingAccount = new Saving();
billsSavingAccount.balance = 99.22;
billsSavingAccount.name = "Bill Simmons";
billsSavingAccount.address = "37 Maple Ave, NN3 3TL";
billsSavingAccount.accountNumber = 5672876;
billsSavingAccount.displayAccountDetails();
}
}
Classes as Extensions
class Loan extends Account{
int loanTerm;
int numberOfRepayments;
double loanSize;
double balance;
double monthlyRepayments;
“extends”
specification
Data elements
Print method
void displayAccountDetails() {
System.out.println("This is a loan account Account number " +
accountNumber);
displayNameAndAddress();
System.out.println("Size of loan " + loanSize);
System.out.println("Number of repayments " + numberOfRepayments);
System.out.println("Outstanding balance " + balance);
System.out.println("Monthly repayments " + monthlyRepayments);
}
}
Running the Multi File Program
• Compile the “extends” class file first
• Then compile the class with the
public static void main (String args[ ])
• Now run this file
Observations
class Loan extends Account{
int loanTerm;
int numberOfRepayments;
double loanSize;
double balance;
double monthlyRepayments;
Note: Data
elements are NOT
specified as
private
void displayAccountDetails ( ) {
System.out.println("This is a loan account Account number " +
accountNumber);
displayNameAndAddress( );
System.out.println("Size of loan " + loanSize);
System.out.println("Number of repayments " + numberOfRepayments);
System.out.println("Outstanding balance " + balance);
System.out.println("Monthly repayments " + monthlyRepayments);
}
}
Observations
class Account {
String name;
String address;
• Saving
instantiation looks like it’s
intobject
accountNumber;
declared as a pointer
void
displayNameAndAddress()
• This is
typical
in Java – it is a pointer. {
System.out.println(name);
• They are automatically
dereferenced
System.out.println(address);
}
Data elements and display
method can be accessed
directly – this is really more
of a struct
public static void main(String args[]) {
Saving billsSavingAccount = new Saving();
billsSavingAccount.balance = 99.22;
billsSavingAccount.name = "Bill Simmons";
billsSavingAccount.address = "37 Maple Ave, NN3 3TL";
billsSavingAccount.accountNumber = 5672876;
billsSavingAccount.displayAccountDetails();
}
}
Creating a New Project with Visual J++ 6.0
• Program opens with New Project window
Choose Console Application
• Specify name for project
•Specify storage location
Creating A New Class
• Select Project, Add Item for dialog box
• Specify name of class
• Name it ProjInfo.java
Click on Open
• Specify item to be a class
• Choose Class
Source Code for the Class
• Enter text for class in open window
public class ProjInfo
{ProjInfo()
{System.out.println("This program computes factorial of number");
System.out.println("passed via command line at a DOS prompt");
System.out.println("Syntax for command line is ");
System.out.print("C:\\Jview Prog1 <integer>\n\n");
System.out.print("Example:
C:\\PROG1 6\n\n");
System.out.print("Program computes, displays 720 which is 6!");
}
}
• Don’t forget to save your work
Creating the Main Class
– Right click on the Class1.java in the
Project Explorer window
– Rename it to Prog1.java
Entering Source Code for Main Class
• Double click on Class1.java to
bring up editing window
• Window will have default
comments in it
Source Code for Main Class
import ProjInfo;
public class Class1
{public ProjInfo intro;
public static void main (String[] args)
{
int count = 1, entered = 1, result = 1;
ProjInfo intro = new ProjInfo();
if (args.length ==1)
count = entered = Integer.parseInt(args[0],10);
else
{
System.out.print("***Error***\n\n");
System.out.print("Please enter:
C:\\Prog1 <integer>\n");
System.exit(0);
}
while (count > 1)
{
result *= count;
count --;
}
System.out.println("The factorial of "+entered+" is "+result);
}
}
Build the Program
• From Build menu,
choose Build
• System will compile and link your program
• When you have a compiler error, double
click in the message window
– Editor will indicate source code line where
error is detected
Running the Program
• From Debug menu,
choose Start
• Program will run
(with an error)
– Window opens
– Displays execution error as specified in code
– Program designed to run from command line
with an argument
C:\JView Class1 6
• Window also immediately closes
Running the Program
• Need to tell Visual Studio interactive
environment to use a
number as our argument
• From Project menu,
select Properties
for dialog box
Properties Dialog Box
Choose Custom radio
button option
Add the argument 6 to
the command line call
• Run the program again (Debug and Start)
– The DOS window still closes immediately