****************************
Code examples for interfaces:
* Class1.java implements Interface1.java
* Abstract Class2.java implements Interface1.java and Interface2.java
* Class3.java extends abstract class Class2.java
* Interface3.java extends Interface1.java and Interface2.java
***************************
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class1.java
~~~~~~~~~~~~~~~~~~~~~~~~~~~
// This class is not abstract, so it must provide
// implementations of method1 and method2.
public class Class1 extends SomeClass
implements Interface1 {
public ReturnType1 method1(ArgType1 arg) {
someCodeHere();
...
}
public ReturnType2 method2(ArgType2 arg) {
someCodeHere();
...
}
...
}
>>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~
Interface1.java
~~~~~~~~~~~~~~~~~~~~~~~~~~
public interface Interface1 {
ReturnType1 method1(ArgType1 arg);
ReturnType2 method2(ArgType2 arg);
}
>>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~~
Abstract Class2.java implements Interface1.java and Interface2.java
~~~~~~~~~~~~~~~~~~~~~~~~~~
Class2.java
~~~~~~~~~~~~~~~~~~~~~~~~~~
// This class is abstract, so does not have to provide
// implementations of the methods of Interface 1 and 2.
public abstract class Class2 extends SomeOtherClass
implements Interface1,
Interface2 {
...
}
>>>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~~~~
Interface2.java
~~~~~~~~~~~~~~~~~~~~~~~~~
public interface Interface2 {
ReturnType3 method3(ArgType3 arg);
}
~~~~~~~~~~~~~~~~~~~~~~~~~
# Class3.java extends abstract class Class2.java
~~~~~~~~~~~~~~~~~~~~~~~~~
Class3.java
>>>>>>>>>>>>>>>>>>>>>>>>>
// This class is not abstract, so it must provide
// implementations of method1, method2, and method3.
public class Class3 extends Class2 {
public ReturnType1 method1(ArgType1 arg) {
someCodeHere();
...
}
public ReturnType2 method2(ArgType2 arg) {
someCodeHere();
...
}
public ReturnType3 method3(ArgType3 arg) {
someCodeHere();
...
}
...
}
>>>>>>>>>>>>>>>>>>>>>>>
# Interface3.java extends Interface1.java and Interface2.java
>>>>>>>>>>>>>>>>>>>>>>>
~~~~~~~~~~~~~~~~~~~~~~
Interface3.java
~~~~~~~~~~~~~~~~~~~~~~
// This interface has three methods (by inheritance) and
// two constants.
public interface Interface3 extends Interface1,
Interface2 {
int MIN_VALUE = 0;
int MAX_VALUE = 1000;
}
<<<<<<<<<<<<<<<<<<<<<
Aug 29
Code examples for interfaces
Aug 29
A Ship class illustrating object-oriented programming concepts
************************
Ship.java A Ship class illustrating object-oriented programming concepts. Incorporates Javadoc comments. See ShipTest.java for a test.
************************
/** Ship example to demonstrate OOP in Java.
*
* @author
* Larry Brown
* @version 2.0
*/
public class Ship {
// Instance variables
private double x=0.0, y=0.0, speed=1.0, direction=0.0;
private String name;
// Constructors
/** Build a ship with specified parameters. */
public Ship(double x, double y, double speed,
double direction, String name) {
setX(x);
setY(y);
setSpeed(speed);
setDirection(direction);
setName(name);
}
/** Build a ship with default values
* (x=0, y=0, speed=1.0, direction=0.0).
*/
public Ship(String name) {
setName(name);
}
/** Move ship one step at current speed/direction. */
public void move() {
moveInternal(1);
}
/** Move N steps. */
public void move(int steps) {
moveInternal(steps);
}
private void moveInternal(int steps) {
double angle = degreesToRadians(direction);
x = x + (double)steps * speed * Math.cos(angle);
y = y + (double)steps * speed * Math.sin(angle);
}
private double degreesToRadians(double degrees) {
return(degrees * Math.PI / 180.0);
}
/** Report location to standard output. */
public void printLocation() {
System.out.println(getName() + " is at (" + getX() +
"," + getY() + ").");
}
/** Get current X location. */
public double getX() {
return(x);
}
/** Set current X location. */
public void setX(double x) {
this.x = x;
}
/** Get current Y location. */
public double getY() {
return(y);
}
/** Set current Y location. */
public void setY(double y) {
this.y = y;
}
/** Get current speed. */
public double getSpeed() {
return(speed);
}
/** Set current speed. */
public void setSpeed(double speed) {
this.speed = speed;
}
/** Get current heading (0=East, 90=North, 180=West,
* 270=South). I.e., uses standard math angles, not
* nautical system where 0=North, 90=East, etc.
*/
public double getDirection() {
return(direction);
}
/** Set current direction (0=East, 90=North, 180=West,
* 270=South). I.e., uses standard math angles,not
* nautical system where 0=North,90=East, etc.
*/
public void setDirection(double direction) {
this.direction = direction;
}
/** Get Ship's name. Can't be modified by user. */
public String getName() {
return(name);
}
private void setName(String name) {
this.name = name;
}
}
*********************
ShipTest.java
*********************
public class ShipTest {
public static void main(String[] args) {
Ship s1 = new Ship("Ship1");
Ship s2 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship2");
s1.move();
s2.move(3);
s1.printLocation();
s2.printLocation();
}
}
Aug 29
Accesses instance variables in a Ship object.
Test1.java Accesses instance variables in a Ship object.
********************************************************
// Create a class with five instance variables (fields):
// x, y, speed, direction, and name. Note that Ship1 is
// not declared "public", so it can be in the same file as
// Test1. A Java file can only contain one "public" class
// definition.
class Ship1 {
public double x, y, speed, direction;
public String name;
}
// The "driver" class containing "main".
public class Test1 {
public static void main(String[] args) {
Ship1 s1 = new Ship1();
s1.x = 0.0;
s1.y = 0.0;
s1.speed = 1.0;
s1.direction = 0.0; // East
s1.name = "Ship1";
Ship1 s2 = new Ship1();
s2.x = 0.0;
s2.y = 0.0;
s2.speed = 2.0;
s2.direction = 135.0; // Northwest
s2.name = "Ship2";
s1.x = s1.x + s1.speed
* Math.cos(s1.direction * Math.PI / 180.0);
s1.y = s1.y + s1.speed
* Math.sin(s1.direction * Math.PI / 180.0);
s2.x = s2.x + s2.speed
* Math.cos(s2.direction * Math.PI / 180.0);
s2.y = s2.y + s2.speed
* Math.sin(s2.direction * Math.PI / 180.0);
System.out.println(s1.name + " is at ("
+ s1.x + "," + s1.y + ").");
System.out.println(s2.name + " is at ("
+ s2.x + "," + s2.y + ").");
}
}
**********************
Aug 29
Application that reports all command-line arguments
******************
ShowArgs.java Application that reports all command-line arguments.
******************
*/
public class ShowArgs {
public static void main(String[] args) {
for(int i=0; i
Aug 29
DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground
DropBall.java Uses a while loop to determine how long it takes a ball to fall from the top of the Washington Monument to the ground
************************************************************
/** Simulating dropping a ball from the top of the Washington
* Monument. The program outputs the height of the ball each
* second until the ball hits the ground.
*
*****************************************
public class DropBall {
public static void main(String[] args) {
int time = 0;
double start = 550.0, drop = 0.0;
double height = start;
while (height > 0) {
System.out.println("After " + time +
(time==1 ? " second, " : " seconds,") +
"the ball is at " + height + " feet.");
time++;
drop = freeFall(time);
height = start - drop;
}
System.out.println("Before " + time + " seconds could " +
"expire, the ball hit the ground!");
}
/** Calculate the distance in feet for an object in
* free fall.
*/
public static double freeFall (float time) {
// Gravitational constant is 32 feet per second squared
return(16.0 * time * time); // 1/2 gt^2
}
}
@@@@@@@@@@@@@@@@@@@@
Aug 29
NumFormat.java Formats real numbers with DecimalFormat.
import java.text.*;
/** Formatting real numbers with DecimalFormat.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class NumFormat {
public static void main (String[] args) {
DecimalFormat science = new DecimalFormat("0.000E0");
DecimalFormat plain = new DecimalFormat("0.0000");
for(double d=100.0; d<140.0; d*=1.10) {
System.out.println("Scientific: " + science.format(d) +
" and Plain: " + plain.format(d));
}
}
}
Aug 29
ModificationTest.java Demonstrates changing fields of an object. Inherits from ReferenceTest.java.
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
import java.awt.Point;
public class ModificationTest extends ReferenceTest {
public static void main(String[] args) {
Point p1 = new Point(1, 2); // Assign Point to p1
Point p2 = p1; // p2 is new reference to *same* Point
print("p1", p1); // (1, 2)
print("p2", p2); // (1, 2)
munge(p2); // Changes fields of the *single* Point
print("p1", p1); // (5, 10)
print("p2", p2); // (5, 10)
}
public static void munge(Point p) {
p.x = 5;
p.y = 10;
}
}
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
import java.awt.Point;
public class ReferenceTest {
public static void main(String[] args) {
Point p1 = new Point(1, 2); // Assign Point to p1
Point p2 = p1; // p2 is new reference to *same* Point
print("p1", p1); // (1, 2)
print("p2", p2); // (1, 2)
triple(p2); // Doesn?t change p2
print("p2", p2); // (1, 2)
p2 = triple(p2); // Have p2 point to *new* Point
print("p2", p2); // (3, 6)
print("p1", p1); // p1 unchanged: (1, 2)
}
public static Point triple(Point p) {
p = new Point(p.x * 3, p.y * 3); // Redirect p
return(p);
}
public static void print(String name, Point p) {
System.out.println("Point " + name + "= (" +
p.x + ", " + p.y + ").");
}
}
Aug 29
Tests the class type of an object using the isInstance method (preferred over instanceof operator).
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
interface Barking {}
class Mammal {}
class Canine extends Mammal {}
class Dog extends Canine implements Barking {}
class Retriever extends Dog {}
public class InstanceOf {
public static void main(String[] args) {
Canine wolf = new Canine();
Retriever rover = new Retriever();
System.out.println("Testing instanceof:");
report(wolf, "wolf");
System.out.println();
report(rover, "rover");
System.out.println("\nTesting isInstance:");
Class barkingClass = Barking.class;
Class dogClass = Dog.class;
Class retrieverClass = Retriever.class;
System.out.println(" Does a retriever bark? " +
barkingClass.isInstance(rover));
System.out.println(" Is a retriever a dog? " +
dogClass.isInstance(rover));
System.out.println(" Is a dog necessarily a retriever? " +
retrieverClass.isInstance(new Dog()));
}
public static void report(Object object, String name) {
System.out.println(" " + name + " is a mammal: " +
(object instanceof Mammal));
System.out.println(" " + name + " is a canine: " +
(object instanceof Canine));
System.out.println(" " + name + " is a dog: " +
(object instanceof Dog));
System.out.println(" " + name + " is a retriever: " +
(object instanceof Retriever));
}
}
Aug 29
URLTest.java Demonstrates try/catch blocks.
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
// Further simplified getURL method.
public URL getURL() {
if (url != null) {
return(url);
}
System.out.print("Enter URL: ");
System.out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String urlString = null;
try {
urlString = in.readLine();
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
} catch(IOException ioe) {
System.out.println("IOError when reading input: " + ioe);
ioe.printStackTrace(); // Can skip return(null) now
} finally {
return(url);
}
}
import java.net.*; // For URL, MalformedURLException
import java.io.*; // For BufferedReader
/** A small class to demonstrate try/catch blocks.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class URLTest {
public static void main(String[] args) {
URLTest test = new URLTest();
test.getURL();
test.printURL();
}
private URL url = null;
/** Read a string from user and create a URL from it. If
* reading fails, give up and report error. If reading
* succeeds but URL is illegal, try again.
*/
public URL getURL() {
if (url != null) {
return(url);
}
System.out.print("Enter URL: ");
System.out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String urlString;
try {
urlString = in.readLine();
} catch(IOException ioe) {
System.out.println("IOError when reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump.
return(null);
}
try {
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
}
return(url);
}
/** Print info on URL. */
public void printURL() {
if (url == null) {
System.out.println("No URL.");
} else {
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
if (protocol.equals("http") && (port == -1)) {
port = 80;
}
String file = url.getFile();
System.out.println("Protocol: " + protocol +
"\nHost: " + host +
"\nPort: " + port +
"\nFile: " + file);
}
}
}
/** Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
// Simplified getURL method.
public URL getURL() {
if (url != null) {
return(url);
}
System.out.print("Enter URL: ");
System.out.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
String urlString = null;
try {
urlString = in.readLine();
url = new URL(urlString);
} catch(MalformedURLException mue) {
System.out.println(urlString + " is not valid.\n" +
"Try again.");
getURL();
} catch(IOException ioe) {
System.out.println("IOError when reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
return(null);
}
return(url);
}
Aug 29
ExecTest.java illustrates use of the Exec class.
/** A test of the Exec class.
*
* Taken from Core Web Programming from
* Prentice Hall and Sun Microsystems Press,
* .
* © 2001 Marty Hall and Larry Brown;
* may be freely used or adapted.
*/
public class ExecTest {
public static void main(String[] args) {
// Note: no trailing "&" -- special shell chars not
// understood, since no shell started. Besides, exec
// doesn?t wait, so the program continues along even
// before Netscape pops up.
Exec.exec("/usr/local/bin/netscape");
// Run commands, printing results.
Exec.execPrint("/usr/bin/ls");
Exec.execPrint("/usr/bin/cat Test.java");
// Don?t print results, but wait until this finishes.
Exec.execWait("/usr/java1.3/bin/javac Test.java");
// Now Test.class should exist.
Exec.execPrint("/usr/bin/ls");
}
}
