Download Designing and Implementing Classes

Document related concepts
no text concepts found
Transcript
Designing and Implementing Classes
Copyright © 2014 by John Wiley & Sons. All rights reserved.
1
Class Methods vs. Instance Methods
 Classes (review):
• A Java program consists of classes.
• Most classes contain both instance variables and
instance methods.
• Any object created from a class will have its own
copy of the class’s instance variables,
• object can call the class’s (public) instance
methods.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
2
Variables in Java
 The variables in java classes:
• Instance variables
• local variables
• Parameter variables
• Class variables
Copyright © 2014 by John Wiley & Sons. All rights reserved.
3
Instance variables (Review)
 Declared in a class, but outside a method, constructor
or any block.
 E.g.
public class Employee{
String name;
.
.
}
 Their values are unique to each instance/object of a
class
 Created when an object is created and destroyed when
the object is destroyed.
 Have default values.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
4
Local Variables
 Declared in the body of a method:
public double giveChange()
{
double change = payment – purchase;
purchase = 0;
Scope/lifetime
of local variable
payment = 0;
return change;
}
 Only visible to the method in which it is declared;
 No default values assigned.
• I.e.You must initialize local variables:
• The compiler complains if you do not
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
Parameter Variables
 Declared in the header of a method:
 E.g.
public void enterPayment(double amount)
 Initialized with the call values/argument values
 Local and parameter variables belong to methods:
• When a method is called/executed, its local and parameter
variables come to life
• When the method exits, they are removed
immediately/lifetime ends
Copyright © 2014 by John Wiley & Sons. All rights reserved.
6
Example: Parameter variable lifetime
amount comes to life 2
3
call enterPayment method
1
method body executes
4 amount life ends
Copyright © 2014 by John Wiley & Sons. All rights reserved.
5
method exits and return control to
next statement in main
7
static/class Variables
 Also called class variables
 Belongs to the class, NOT to any object of the class.
 E.g.
• class variable lastAssignedNumber assign bank account
numbers sequentially
 Declare it using the static reserved word
AccessModifier static type variableName [= value];
 E.g.
private static int lastAssignedNumber;
Copyright © 2014 by John Wiley & Sons. All rights reserved.
8
static Variables
 created when its class or interface is prepared
 initialized to a default value.
 Life ends when its class is unloaded.
 Example:
public class BankAccount
{
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 0;
public BankAccount(double balance)
{
this.balance = balance;
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
. . .
Copyright
} © 2014 by John Wiley & Sons. All rights reserved.
9
static Variables
 Every BankAccount object has its own balance and
accountNumber instance variables
 All objects share a single copy of the
lastAssignedNumber variable (static/class variable)
 That variable is stored in a separate location, outside any
BankAccount objects
Copyright © 2014 by John Wiley & Sons. All rights reserved.
10
static Variables and Methods
Figure 5 A static Variable and Instance Variables
Copyright © 2014 by John Wiley & Sons. All rights reserved.
11
How to Access a static variable
 Class variables are referenced by the class name itself.
 E.g. (lastAssignedNumber should be public)
BankAccount. lastAssignedNumber
 This makes it clear that they are class variables.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
12
Programming Question
 Modify BankAccount class to incorporate an
accountNumber variable (and lastAssignedNumber ).
Implement a toString method that returns a string
with the String representation of class(E.g. “Bank
Account No:1 balance:1000.0”).
 Modify BankAccountTester class to create three bank
accounts with different balances and print the details
of each bank account by calling toString method.
 A sample run is shown:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
13
Answer
BankAccount.java
public class BankAccount
{
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 0;
public BankAccount(double balance)
{
this.balance = balance;
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
public String toString()
{
return "Bank Account No:"+accountNumber+" balance:"+balance;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
14
Answer
BankAccountTester.java
public class BankAccountTester
{
public static void main(String args[])
{
BankAccount acct1 = new BankAccount(1000.00);
BankAccount acct2 = new BankAccount(2000.00);
BankAccount acct3 = new BankAccount(3000.00);
System.out.println(acct1.toString());
System.out.println(acct2);
System.out.println(acct3);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
15
static Constants
 static variables:
• Should always be declared as private,
• This ensures that methods of other classes do not change their
values
 static constants:
• May be either private or public
public class BankAccount
{
public static final double OVERDRAFT_FEE = 29.95;
. . .
}
• Methods from any class can refer to the constant as
BankAccount.OVERDRAFT_FEE
Copyright © 2014 by John Wiley & Sons. All rights reserved.
16
Question
Name two static variables of the System class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
17
Answer
Name two static variables of the System class.
Answer: System.in and System.out.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
18
Question
Name a static constant of the Math class.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
19
Answer
Name a static constant of the Math class.
Answer: Math.PI
Copyright © 2014 by John Wiley & Sons. All rights reserved.
20
Mathods in Java
 The methods in java classes:
• Instance methods
• Class methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.
21
Instance Methods (Review)
 An instance method may access the instance
variables in an object without changing them, or
it may modify instance variables.
 If acct is a reference to BankAccount object:
BankAccount acct = new BankAccount();
then the call
acct.deposit(1000.00);
deposits $1000 into the Account object that
acct represents.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
22
Class/static Methods
 A class method—like all methods in Java—must belong to
a class.
 Class methods do not require access to instance variables
(has nothing to do with objects).
Copyright © 2014 by John Wiley & Sons. All rights reserved.
23
Question
The following method computes the average of two
numbers:
public static double average(double a, double b)
Why should it not be defined as an instance method?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
24
Answer
Answer: The method needs no data of any object. The
only required input is the values argument.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
25
Class Methods
 Many classes in the Java API provide class methods,
including :
• Math,
• System, and
• String.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
26
Example: The Math Class
 The Math class contains no instance variables and no
instance methods.
• How would you know just by looking at Java API?
 It’s just a repository for math functions (class methods)
and math constants.
 The Math class is not instantiable.
• You cannot create objects from Math class.
• How do you know?
• No constructors in API page and
• ALL methods in API page are class methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.
27
 Some Math class methods:
Math.abs
Math.max
Math.min
Math.pow
Math.round
Math.sqrt
Copyright © 2014 by John Wiley & Sons. All rights reserved.
28
28
Modifier=static
indicates the
method is a
class method
Copyright © 2014 by John Wiley & Sons. All rights reserved.
29
How to call a static/class method
 Syntax to call a class method:
ClassName.classmethodName([arguments]);
 E.g.
Math.abs(-10);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
30
Programming Question
 Write a tester program EquationSolver.java to calculate
and the two roots of the equation:
• Define a=1, b=-3, c=-4
• Sample output:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
31
Answer
EquationSolver.java
public class EquationSolver
{
public static void main(String args[])
{
int a = 1, b =-3, c=-4;
double root1 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
double root2 = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);
System.out.println("root1="+root1);
System.out.println("root2="+root2);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
32
Example: The System Class
 The System class contains a number of class methods,
including exit, which causes program termination.
 A call of System.exit:
System.exit(0);
 The argument (an int value) is a status code that can be
tested after program termination.
 By convention, 0 indicates normal termination. Any other
value (such as –1) indicates abnormal termination.
 The System class is not instantiable.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
33
Copyright © 2014 by John Wiley & Sons. All rights reserved.
34
Question
 Is String class instantiable?
Copyright © 2014 by John Wiley & Sons. All rights reserved.
35
Answer
 Yes
 String is an example of a class that contains both
instance methods and class methods.
 Notice also you have constructors listed in API
Copyright © 2014 by John Wiley & Sons. All rights reserved.
36
Example: The String Class
 Java’s String class contains several overloaded class
methods named valueOf that convert different types
of data to string form.
 E.g.:
String intString = String.valueOf(607);
String doubleString = String.valueOf(4.5);
The value of intString will be "607" and the value of
doubleString will be "4.5".
Copyright © 2014 by John Wiley & Sons. All rights reserved.
37
Class methods
Copyright © 2014 by John Wiley & Sons. All rights reserved.
38
Method Rules
Static Methods:
Instance Methods:
can access static members (static same
variables + static methods)in class.
CANNOT access instance members can access instance members of
(instance variables + instance
the same instance.
methods) in the same class.
Can access instance members of
same
another instance via that instance
of the class
Copyright © 2014 by John Wiley & Sons. All rights reserved.
39
Writing Class Methods
 Writing a class method is similar to writing an instance
method, except that the declaration of a class method
must contain the keyword static.
 Parts of a class method declaration:
•
•
•
•
•
•
Access modifier
The word static
Result type
Method name
Parameters
Body
Copyright © 2014 by John Wiley & Sons. All rights reserved.
40
Declaring Class Methods
 Syntax
accessModifier static returnType methodName([arguments])
{
//your code here
}
 Example of a class method declaration:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
41
Example Class Method
public class MyMath
{
public static int calculateSum(int a, int b)
{
return (a+b);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
42
Programming Question
 Modify the BankAccount class to do following:
• Add a static method getLastAssignedNumber that returns
the total number of accounts. (Think about why this method
should be static - its information is not related to any
particular account.)
 Modify BankAccountTester class to call this method
and print total accounts created (i.e. last assigned
Bank Account No.).
 Sample run:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
43
Answer
BankAccount.java
public class BankAccount
{
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 0;
public BankAccount()
this(0.0);
}
{
public BankAccount(double initialBalance)
balance = initialBalance;
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
{
public static int getLastAssignedNumber()
{
return lastAssignedNumber;
}
public String toString()
{
return "Bank Account No:"+accountNumber+" balance:"+balance;
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
44
Answer
BankAccountTester.java
public class BankAccountTester
{
public static void main(String args[])
{
BankAccount acct1 = new BankAccount(1000.00);
BankAccount acct2 = new BankAccount(2000.00);
BankAccount acct3 = new BankAccount(3000.00);
System.out.println(acct1.toString());
System.out.println(acct2);
System.out.println(acct3);
System.out.println("Last Assigned Bank Account Number="+BankAccount.getLastAssignedNumber());
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
45
Packages
 Package: Set of related classes
 Important packages in the Java library:
/opt/java-jdk/src.zip
Copyright © 2014 by John Wiley & Sons. All rights reserved.
46
Organizing Related Classes into Packages
In Java, related classes are
grouped into packages.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
47
Organizing Related Classes into Packages
 To put classes in a package, you must place a line
package packageName;
as the first instruction in the source file containing the
classes.
 Package name
• consists of one or more identifiers separated by periods.
• Usually all lower case
Copyright © 2014 by John Wiley & Sons. All rights reserved.
48
 To put the Financial class into a package named
com.horstmann.bigjava, the Financial.java file
must start as follows:
package com.horstmann.bigjava;
public class Financial
{
. . .
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
49
Organizing Related Classes into Packages
 A special package: default package
• Has no name
• No package statement
• If you did not include any package statement at the top of your
source file
o its classes are placed in the default package.
Copyright © 2014 by John Wiley & Sons. All rights reserved.
50
Package Names
 Package names should be unique.
 Use packages to avoid name clashes:
java.util.Timer
vs.
javax.swing.Timer
 A good choice for package name:
• turn the domain name in reverse:
com.horstmann.bigjava
• Or write your email address backwards:
edu.sjsu.cs.walters
Copyright © 2014 by John Wiley & Sons. All rights reserved.
51
Syntax 8.1 Package Specification
Copyright © 2014 by John Wiley & Sons. All rights reserved.
52
Packages and Source Files
package com.horstmann.bigjava;
public class Financial{
. . .
}
Financial.java
Command line compilation command:
javac -d . BankAccount.java
Place .java file anywhere you want
(base directory)
Financial.java
com
horstmann
Path MUST matches the package name
bigjava
Copyright © 2014 by John Wiley & Sons. All rights reserved.
Financial.class
53
Programming Question
 Create a package cs160:
1. Modify BankAccount.java to include the package statement:
package csbsju.cs160;
2. Compile these two files in a terminal window:
javac -d . BankAccount.java
•
This will automatically create the directory structure and
place .class file in csbsju/cs160 directory.
• Use BankAccount class template (with a main) in next slide
 Test if classes work from Base directory:
java csbsju.cs160.BankAccount
Copyright © 2014 by John Wiley & Sons. All rights reserved.
54
Use following template:
public class BankAccount
{
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 0;
public BankAccount(double balance)
{
this.balance = balance;
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
public String toString()
{
return "Bank Account No:"+accountNumber+" balance:"+balance;
}
public static void main(String args[])
{
BankAccount acct1 = new BankAccount(1000.00);
BankAccount acct2 = new BankAccount(2000.00);
BankAccount acct3 = new BankAccount(3000.00);
System.out.println(acct1.toString());
System.out.println(acct2);
System.out.println(acct3);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
55
Answer
BankAccount.java
package csbsju.cs160;
public class BankAccount{
private double balance;
private int accountNumber;
private static int lastAssignedNumber = 0;
public BankAccount(double balance)
{
this.balance = balance;
lastAssignedNumber++;
accountNumber = lastAssignedNumber;
}
public String toString()
{
return "Bank Account No:"+accountNumber+" balance:"+balance;
}
public static void main(String args[])
{
BankAccount acct1 = new BankAccount(1000.00);
BankAccount acct2 = new BankAccount(2000.00);
BankAccount acct3 = new BankAccount(3000.00);
System.out.println(acct1.toString());
System.out.println(acct2);
System.out.println(acct3);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
56
Answer

Testing
Copyright © 2014 by John Wiley & Sons. All rights reserved.
57
Create a package
 Add package to jar file list
1. Create the jar file
• In the terminal go to base directory and type:
jar cvf cs160.jar csbsju/cs160/*.class
Read more on jar files:
http://docs.oracle.com/javase/tutorial/deployment/jar/
Read more on setting an Application's Entry Point (using manifest file:):
http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
Copyright © 2014 by John Wiley & Sons. All rights reserved.
58
Create a package
2. Add jar to classpath in DrJava:
•
EditPreferencesResourceLocationsExtraClassPathAddselect cs160.jar ok

Copyright © 2014 by John Wiley & Sons. All rights reserved.
59
Importing Packages
 Can use a class without importing: refer to it by its full
name (package name + class name):
java.util.Scanner in = new java.util.Scanner(System.in);
• Inconvenient
 import directive lets you refer to a class of a package by
its class name, without the package prefix:
import java.util.Scanner;
• Now you can refer to the class as Scanner without the package
prefix.
• E.g. Scanner in = new Scanner(System.in);
Copyright © 2014 by John Wiley & Sons. All rights reserved.
60
Importing Packages
 Can import all classes in a package:
import csbsju.cs160.*;
 Never need to import
java.lang.
 You don't need to import other classes in the same
package .
Copyright © 2014 by John Wiley & Sons. All rights reserved.
61
Programming Question
 Import packages:
• Write a tester class called PackageImportDemo which will test
importing packages (save this class in a completely different
location than the location you have source/.class files for cs160
package you created)
• Import the package you created and test BankAccount class by
creating a BankAccount object with balance $1000 and printing
the balance by calling toString() method:
Copyright © 2014 by John Wiley & Sons. All rights reserved.
62
Answer
PackageImportDemo.java
import csbsju.cs160.BankAccount;
public class PackageImportDemo
{
public static void main(String args[])
{
BankAccount acct = new BankAccount(1000.0);
System.out.println(acct);
}
}
Copyright © 2014 by John Wiley & Sons. All rights reserved.
63
References
 Beginning Java Objects, KN King
 http://docs.oracle.com/javase/specs/jls/se7/html/jls4.html#jls-4.12.3
Copyright © 2014 by John Wiley & Sons. All rights reserved.
64