Upload
knox-howard
View
37
Download
0
Embed Size (px)
DESCRIPTION
Class Design Lesson - 4. CSM-Java Programming-I Spring,2005. Objectives Review of last class Method Overloading Constructor Overloading Static revisited finalize Recursion Command-Line Arguments Arrays Class Design. CSM-Java Programming-I Lesson-1. - PowerPoint PPT Presentation
Citation preview
CSM-Java Programming-I Spring,2005
Class Design
Lesson - 4
CSM-Java Programming-I Lesson-1
Objectives• Review of last class
• Method Overloading
• Constructor Overloading
• Static revisited
• finalize
• Recursion
• Command-Line Arguments
• Arrays
• Class Design
CSM-Java Programming-I Lesson-1
Method Overloading
• In Java, it is possible for two or more methods to have the same name, as long as they have different number or types of parameters. This is called method overloading.
• When an overloaded method is invoked, the compiler compares the number and types of parameters to find the method that best matches the available signatures.
• The return type and the exceptions thrown are not counted for overloading of methods.
CSM-Java Programming-I Lesson-1
Method Overloading
public class Example {
public void show() {
// does something;
}
public double show (double i) {
// does something else
return i/2.0;
}
}
CSM-Java Programming-I Lesson-1
Constructor Overloading
public class Box {int height;int width;int depth;
public Box () {height = 0;….
}
public Box(int bheight, int bwidth, int bdepth) {height = bheight;…….
}
CSM-Java Programming-I Lesson-1
Static Revisited
• When a member is declared static, it can be accessed before any objects of its class are created.
• Both methods and variables can be declared static.
• A static member is a member that is only one per class, rather than one in every object created from that class.
• A static method can access only static variables and static methods of the class.
• There is no this reference because there is no specific object being operated on.
• classname.staticmethod();
CSM-Java Programming-I Lesson-1
Garbage collection and finalize
• Java performs garbage collection and eliminates the need to free objects explicitly.
• When an object has no references to it anywhere, except in other objects that are also unreferenced, its space can be reclaimed.
• Before the object is destroyed, it might be necessary for the object to perform some actions. For example closing an opened file. In such a case define a finalize() method with the actions to be performed before the object is destroyed.
CSM-Java Programming-I Lesson-1
finalize
• When a finalize method is defined in a class, Java run time calls finalize() whenever it is about to recycle an object of that class.
protected void finalize(){
// code}
• A garbage collector reclaims objects in any order or never reclaim them.
CSM-Java Programming-I Lesson-1
Command-Line Arguments
• The data that follows the program name on the command-line when it is executed is a command-line argument.
• The command-line arguments are stored as strings in the String array passed to the main().
CSM-Java Programming-I Lesson-1
Command-Line Arguments
public class Example {
public static void main(String args[]) {
for (int i=0; i < args.length; i++)
System.out.println(“args[“ + i + “]: “ + args[i]);
}
}
> java Example my test 1
args[0]: my
args[1]: test
args[2]: 1
CSM-Java Programming-I Lesson-1
Arrays
• An array is a fixed-length collection of variables of the same type.
• Arrays can have one or more dimensions.
• An element in an array is accessed by its index. E.g.: a[i]
int[] data = new int[10];
• Arrays have a length field that says how many elements the array contains. In the above example: data.length =10
CSM-Java Programming-I Lesson-1
Arrays
• An array range is between 0 and length-1. An indexOutofBoundsException is thrown if you try to access elements outside the range of the array.
• An array can be initialized when they are declared.
Eg: int singleDigitEvenNumbers[] = {2, 4, 6, 8 };
• In the above example there is no need to do “new”. An array will be created large enough to hold all the elements that are initialized.
CSM-Java Programming-I Lesson-1
Recursion
Recursion is defining something in terms of itself (a method to call itself).
public class Factorial {public int fact(int n) {
int result;if (n == 1) {
return 1;}result = fact(n-1) * n;return result;
}}
CSM-Java Programming-I Lesson-1
Class Design
• Classes are collections of objects.
• Objects are entities not actions.
• Methods are actions.
• A class should be a single concept.
• Begin designing your class by identifying objects and the classes to which they belong.
CSM-Java Programming-I Lesson-1
Class Design
• Some examples of classes can be, Student, Employee, etc.,
• Very occasionally, a class has no objects, but it contains a collection of related static methods and constants.
-Math class is an example of such a class. It is called a utility class.
• If you can’t tell from the class name what an object of the class is supposed to do, then you are probably not on the right track.
CSM-Java Programming-I Lesson-1
Cohesion
• The public interface of a class should be cohesive (all features should be closely related to the single concept that the class represents).
CSM-Java Programming-I Lesson-1
Example
/** A purse computes the total value of a collection of coins.*/public class Purse {
private double total;
/** Constructs an empty purse. */ public Purse() { total = 0; }
CSM-Java Programming-I Lesson-1
Example
/**Add a coin to the purse.
@param aCoin the coin to add*/
public void add(Coin aCoin) {total = total + aCoin.getValue();
}
/**Get the total value of the coins in the purse.@return the sum of all coin values
*/public double getTotal() {
return total;}
}
CSM-Java Programming-I Lesson-1
Example
/** A coin with a monetary value.*/public class Coin {
private double value;private String name;
/** Constructs a coin. @param aValue the monetary value of the coin. @param aName the name of the coin */ public Coin(double aValue, String aName) { value = aValue; name = aName; }
CSM-Java Programming-I Lesson-1
Example
/** Gets the coin value. @return the value */ public double getValue() { return value; } /** Gets the coin name. @return the name */ public String getName() { return name; }}
CSM-Java Programming-I Lesson-1
Coupling
• A class depends on another class if it uses objects of that other class.
• If many classes of a program depend on each other, then we say that the coupling between classes is high.
• It is a good practice to minimize coupling between classes.
• Follow a consistent scheme for the method names and parameters.
CSM-Java Programming-I Lesson-1
Accessor and Mutator Methods
• A method that accesses an object and returns some information about it, without changing the object, is called an accessor method. Eg: getBalance() method in BankAccount class.
• A method whose purpose is to modify the state of an object is called a mutator method. Eg: withdraw() or deposit()
• Some classes are designed to have only accessor methods. Eg: String. – Immutable class.
CSM-Java Programming-I Lesson-1
Preconditions
• A precondition is a requirement that the caller of a method must obey.
• For example, the deposit method of the BankAccount class has a precondition amount >= 0 (amount parameter must not be negative)
• If a method violates this precondition it is not responsible for computing a correct result (might throw an exception).
CSM-Java Programming-I Lesson-1
Postconditions
• Postcondition makes a statement about the object's state after the deposit method is called.
• For example, the deposit method of the BankAccount class has a postcondition getBalance() >= 0 (balance returned after deposit is not negative).
• As long as the precondition is fulfilled, this method guarentees that the balance after the deposit is not negative.
CSM-Java Programming-I Lesson-1
Scope
• The scope of local variables extends from the point of declaration to the end of the block that encloses it.
• The scope of a variable in a for loop extends to the for loop but not beyond.
for (int i = 1; i <= years; i++)
{
……
} // scope of i ends here.
CSM-Java Programming-I Lesson-1
Scope
• In Java, you cannot have two local variables with overlapping scope.
Rectangle r = new Rectangle (5, 10, 20, 30);if (x >= 0){
double r = Math.sqrt(x);// Error- Can’t declare another variable
called r here.……
}
CSM-Java Programming-I Lesson-1
Scope of Class Memebrs
• In Java, the scope of a local variable and an instance variable can overlap. You can solve this problem by using the this reference.
public class Coin {
double value;
String name;
public Coin (double value, String name) {
this.value = value;
this.name = name;
}
CSM-Java Programming-I Lesson-1
Calling One Constructor from Another
public class Coin {public Coin( double value , String name) {
this.value = value;this.name = name;
}public Coin() {
this (1, “dollar”);}…..
}
Such a constructor call can occur only as the first line in another constructor.
CSM-Java Programming-I Lesson-1
Packages
• A package is a set of related classes. They provide a structuring mechanism.
• To put classes in a package, you must place a line
package packagename;
package com.hotsmann.bigjava;
as the first line in the source file containing classes.
• If you did not include package statement at the top of your source file, its classes are placed in the default package.
CSM-Java Programming-I Lesson-1
Importing packages
• The import directive lets you refer to a class of a package by its class name, without the package prefix.
import java.awt.Color;
• There is no need to import the classes in the java.lang package explicitly. This package contains most basic Java classes.
• There is no need to import the other classes in the same package.
CSM-Java Programming-I Lesson-1
How to program with packages
• Step 1: Come up with a package name : Say homework1.
• Step 2: Pick a base directory: Say C:\CIS381\Assignments
• Step 3: Make a subdirectory from the base directory that matches your package name.
mkdir C:\CIS381\Assignments\homework1
• Step 4: Place your source files into the package subdirectory.
Say your homework1 consists of BankAccount.java and BankAccountTest.java, then put them in C:\CIS381\Assignments\homework1
CSM-Java Programming-I Lesson-1
How to program with packages
• Step 5: Use the package statement in each of your source files.
package homework1; as the first line of code in your BankAccount.java and BankAccountTest.java.
• Step 6: Change to the base directory to compile your files.
cd \CIS381\Assigments
javac homework1\BankAccount.java
javac homework1\BankAccountTest.java
CSM-Java Programming-I Lesson-1
How to program with packages
• Step 7: Run your program from the base directory
cd CIS381/Assignments
java homework1.BankAccountTest