+ All Categories
Home > Documents > CSM-Java Programming-I Spring,2005

CSM-Java Programming-I Spring,2005

Date post: 31-Dec-2015
Category:
Upload: knox-howard
View: 35 times
Download: 0 times
Share this document with a friend
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
33
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4
Transcript
Page 1: CSM-Java Programming-I                            Spring,2005

CSM-Java Programming-I Spring,2005

Class Design

Lesson - 4

Page 2: CSM-Java Programming-I                            Spring,2005

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

Page 3: CSM-Java Programming-I                            Spring,2005

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.

Page 4: CSM-Java Programming-I                            Spring,2005

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;

}

}

Page 5: CSM-Java Programming-I                            Spring,2005

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;…….

}

Page 6: CSM-Java Programming-I                            Spring,2005

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();

Page 7: CSM-Java Programming-I                            Spring,2005

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.

Page 8: CSM-Java Programming-I                            Spring,2005

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.

Page 9: CSM-Java Programming-I                            Spring,2005

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().

Page 10: CSM-Java Programming-I                            Spring,2005

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

Page 11: CSM-Java Programming-I                            Spring,2005

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

Page 12: CSM-Java Programming-I                            Spring,2005

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.

Page 13: CSM-Java Programming-I                            Spring,2005

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;

}}

Page 14: CSM-Java Programming-I                            Spring,2005

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.

Page 15: CSM-Java Programming-I                            Spring,2005

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.

Page 16: CSM-Java Programming-I                            Spring,2005

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).

Page 17: CSM-Java Programming-I                            Spring,2005

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; }

Page 18: CSM-Java Programming-I                            Spring,2005

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;}

}

Page 19: CSM-Java Programming-I                            Spring,2005

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; }

Page 20: CSM-Java Programming-I                            Spring,2005

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; }}

Page 21: CSM-Java Programming-I                            Spring,2005

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.

Page 22: CSM-Java Programming-I                            Spring,2005

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.

Page 23: CSM-Java Programming-I                            Spring,2005

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).

Page 24: CSM-Java Programming-I                            Spring,2005

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.

Page 25: CSM-Java Programming-I                            Spring,2005

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.

Page 26: CSM-Java Programming-I                            Spring,2005

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.……

}

Page 27: CSM-Java Programming-I                            Spring,2005

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;

}

Page 28: CSM-Java Programming-I                            Spring,2005

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.

Page 29: CSM-Java Programming-I                            Spring,2005

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.

Page 30: CSM-Java Programming-I                            Spring,2005

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.

Page 31: CSM-Java Programming-I                            Spring,2005

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

Page 32: CSM-Java Programming-I                            Spring,2005

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

Page 33: CSM-Java Programming-I                            Spring,2005

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


Recommended