Você está na página 1de 79

Introduction to Object-Oriented Programming, Sample

Programs, Set 1
Published: November 29, 2001
Revised: June 1, 2005
By Richard G. Baldwin

Java Programming Tutorial # 9000

• Preface
• Sample Programs
• About the Author

Preface
This is the first in a miniseries of lessons designed specifically to help the students in my
"Introduction to Object-Oriented Programming" course study for their exams. However,
others may find the lesson useful as well.

The lesson consists of a set of simple programs, each designed to illustrate one or more
important Java OOP concepts. The concepts involved are identified in the comments at
the beginning of each program.

The programs are designed to illustrate the code without providing a detailed discussion
of the code. You are referred to the other lessons in my online Java tutorials for detailed
discussions of the OOP concepts illustrated by these programs.

Sample Programs
Program Samp002.java

/*File Samp002
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Write Java application
The main method
Display String literal on console

The output consists of the following


line of text on the screen:
Hello World

**************************************/

class Samp002{
public static void main(
String[] args){
System.out.println("Hello World");
}//end main
}//end class Samp002

Program Samp004.java

/*File Samp004
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiate object of existing class
Invoke method on object

The output consists two lines of text


similar to the following. The first
line will show the current date and
time. The second line will show the
number of milliseconds since Jan 1,
1970.

Wed Nov 28 13:50:50 CST 2001


1006977050803

**************************************/

import java.util.*;
class Samp004{
public static void main(
String[] args){
//Instantiate object of Date class
Date refVar = new Date();
System.out.println(refVar);
long primVar = refVar.getTime();
System.out.println(primVar);
}//end main
}//end class Samp004

Program Samp006.java

/*File Samp006
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiate anonymous Date object
Invoke method on anonymous Date
object to get long value
Pass long value to constructor
for Random class
Invoke method on object of
Random class to get random
int value
Display random int value

The output consists of a single random


value similar to the following:

472076870

**************************************/

import java.util.*;
class Samp006{
public static void main(
String[] args){
Random refVar2 =
new Random(new Date().getTime());
System.out.println(
refVar2.nextInt());
}//end main
}//end class Samp006

Program Samp008.java

/*File Samp008
Copyright 2001, R.G.Baldwin
Rev 06/01/05

Tested using JDK 1.3 under Win

Illustrates:
Instantiate anonymous Date object
Invoke method on anonymous Date
object to get long value
Pass long value to constructor
for Random class
Invoke method on object of
Random class to get random
int value
Use cast operator to convert random
int value to type byte
Display random byte value
The output consists of a single random
value similar to the following:

110

**************************************/

import java.util.*;
class Samp008{
public static void main(
String[] args){
Random refVar2 =
new Random(new Date().getTime());
System.out.println(
(byte)refVar2.nextInt());
}//end main
}//end class Samp008

Program Samp010.java

/*File Samp010
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Array objects
Conversion from int to double
during division of int value
by double value

The output consists of the following


four lines of text on the screen.
Note that three of the values are
integer values while one is a floating
value.

0
1
2.0
3

**************************************/

class Samp010{
public static void main(
String[] args){
int[] arrayRef = new int[4];
for(int cnt=0;cnt<arrayRef.length;
cnt++){
arrayRef[cnt] = cnt;
}//end for loop
for(int cnt=0;cnt<arrayRef.length;
cnt++){
if(cnt == 2)
System.out.println(
arrayRef[cnt]/1.0 + " ");
else
System.out.println(
arrayRef[cnt] + " ");
}//end for loop
}//end main
}//end class Samp010

Program Samp012.java

/*File Samp012
Copyright 2001, R.G.Baldwin
Rev 06/01/05

Tested using JDK 1.3 under Win

Illustrates:
Reference variables
Defining new classes
Instantiating objects of new
classes
Overriding toString method in one
new class, but not the other
Invoking toString method on objects
of both new classes and displaying
the results

The output consists of the following


two lines of text:

Richard Baldwin
Samp012ClassB@273d3c

**************************************/

import java.util.*;
class Samp012{
public static void main(
String[] args){
Samp012ClassA refVar1 =
new Samp012ClassA();
String stringVar =
refVar1.toString();
System.out.println(stringVar);

Samp012ClassB refVar2 =
new Samp012ClassB();
stringVar = refVar2.toString();
System.out.println(stringVar);
}//end main
}//end class Samp012
//===================================//

class Samp012ClassA{
//overridden toString method
public String toString(){
return "Richard Baldwin";
}//end overridden toString()
}//end class Samp012ClassA
//===================================//
class Samp012ClassB{
//no overridden toString method
}//end class Samp012ClassB

Program Samp014.java

/*File Samp014
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Defining a noarg constructor

The output consists of the following


line of text:

Richard Baldwin

**************************************/

import java.util.*;
class Samp014{
public static void main(
String[] args){
new Samp014MyClass();
}//end main
}//end class Samp014
//===================================//

class Samp014MyClass{

Samp014MyClass(){//constructor
System.out.println(
"Richard Baldwin");
}//end constructor

}//end class Samp014MyClass

Program Samp016.java
/*File Samp016
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Defining a parameterized constructor

The output consists of the following


line of text:

Richard Baldwin

**************************************/

import java.util.*;
class Samp016{
public static void main(
String[] args){
new Samp016MyClass(
"Richard Baldwin");
}//end main
}//end class Samp016
//===================================//

class Samp016MyClass{

//parameterized constructor
Samp016MyClass(String dataIn){
System.out.println(dataIn);
}//end constructor

}//end class Samp016MyClass

Program Samp018.java

/*File Samp018
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Class variables
Accessing class variable using
class name
Accessing class variable using
reference to object
Only one copy of class variable
exists regardless of number of
objects instantiated from the
class (including none)
The output consists of the following
six lines of text:

6
6
6
12
12
12

**************************************/

import java.util.*;
class Samp018{
public static void main(
String[] args){
Samp018MyClass.classVar = 6;
System.out.println(
Samp018MyClass.classVar);

Samp018MyClass refVar1 =
new Samp018MyClass();
System.out.println(
refVar1.classVar);

Samp018MyClass refVar2 =
new Samp018MyClass();
System.out.println(
refVar2.classVar);

refVar2.classVar = 12;
System.out.println(
Samp018MyClass.classVar);
System.out.println(
refVar1.classVar);
System.out.println(
refVar2.classVar);
}//end main
}//end class Samp018
//===================================//

class Samp018MyClass{
static int classVar;
}//end class Samp018MyClass

Program Samp020.java

/*File Samp020
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Instance variables
Cannot access instance variable using
class name
Accessing instance variable using
reference to object
Every object has its own copy of each
instance variable

The output consists of the following


six lines of text:

6
12
10
20

**************************************/

import java.util.*;
class Samp020{
public static void main(
String[] args){
//Following statements produce
// compiler errors
// Samp020MyClass.instanceVar = 6;
// System.out.println(
// Samp020MyClass.instanceVar);

Samp020MyClass refVar1 =
new Samp020MyClass();
refVar1.instanceVar = 6;
System.out.println(
refVar1.instanceVar);

Samp020MyClass refVar2 =
new Samp020MyClass();
refVar2.instanceVar = 12;
System.out.println(
refVar2.instanceVar);

refVar1.instanceVar = 10;
refVar2.instanceVar = 20;
System.out.println(
refVar1.instanceVar);
System.out.println(
refVar2.instanceVar);
}//end main
}//end class Samp020
//===================================//

class Samp020MyClass{
int instanceVar;
}//end class Samp020MyClass
Program Samp022.java

/*File Samp022
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Overloaded class methods

The output consists of the following


four lines of text on the screen.

6
2.727272727272727
6
2.727272727272727

**************************************/

import java.util.*;
class Samp022{
public static void main(
String[] args){
int intVar = 6;
double doubleVar = 6/2.2;
System.out.println(intVar);
System.out.println(doubleVar);

Samp022MyClass.store(intVar);
System.out.println(
Samp022MyClass.fetchIntData());

Samp022MyClass.store(doubleVar);
System.out.println(
Samp022MyClass.fetchDoubData());

}//end main
}//end class Samp022
//===================================//

class Samp022MyClass{
private static int classIntVar;
private static double classDoubleVar;

//overloaded class method


static void store(int dataIn){
classIntVar = dataIn;
}//end store

//overloaded class method


static void store(double dataIn){
classDoubleVar = dataIn;
}//end store

//class method
static int fetchIntData(){
return classIntVar;
}//end fetchIntData

//class method
static double fetchDoubData(){
return classDoubleVar;
}//end fetchDoubData
}//end class Samp022MyClass

Program Samp024.java

/*File Samp024
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Overloaded instance methods

The output consists of the following


two lines of text:

3
8

**************************************/

import java.util.*;
class Samp024{
public static void main(
String[] args){
Samp024MyClass refVar1 =
new Samp024MyClass();

refVar1.setData(3);
System.out.println(
refVar1.getData());
refVar1.setData(new Integer(8));
System.out.println(
refVar1.getData());

}//end main
}//end class Samp024
//===================================//

class Samp024MyClass{
private int instanceVar;
//overloaded instance method
void setData(int dataIn){
instanceVar = dataIn;
}//end setData()

//overloaded instance method


void setData(Integer dataIn){
instanceVar = dataIn.intValue();
}//end setData()

int getData(){
return instanceVar;
}//end getData()
}//end class Samp024MyClass

Program Samp030.java

/*File Samp030
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Reference variables
Class variables
Instance variables
Noarg constructor
Class methods
Instance methods
Overridden toString method
Overloaded class methods
Overloaded instance methods
Instantiating objects
Display on console
Invoking methods on anonymous objects
Array objects
Casting
Conversion from int to double
during division
Invoking class methods using class
name
Invoking instance methods using
reference to object

The output consists of the following


five lines of text on the screen.
Because the program uses random
data, the actual values will differ
from one run to the next.

Samp030
Richard
Baldwin
-78 -81.0 -51 -61
-78 -81.0 -51 -61

**************************************/

import java.util.*;
class Samp030{
public static void main(
String[] args){
Samp030MyClass refVar1 =
new Samp030MyClass();
System.out.println(refVar1);

Random refVar2 =
new Random(new Date().getTime());
int[] arrayRef = new int[4];
for(int cnt=0;cnt<arrayRef.length;
cnt++){
arrayRef[cnt] =
(byte)refVar2.nextInt();
if(cnt==1)
System.out.print(
arrayRef[cnt]/1.0 + " ");
else
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();

Samp030MyClass.store(arrayRef[0]);
System.out.print(
Samp030MyClass.fetchIntData()
+ " ");
Samp030MyClass.store(
arrayRef[1]/1.0);
System.out.print(
Samp030MyClass.fetchDoubleData()
+ " ");
refVar1.setData(arrayRef[2]);
System.out.print(
refVar1.getData() + " ");
refVar1.setData(
new Integer(arrayRef[3]));
System.out.println(
refVar1.getData());

}//end main
}//end class Samp030
//===================================//

class Samp030MyClass{
private static int classIntVar;
private static double classDoubleVar;
private int instanceVar;

Samp030MyClass(){//constructor
System.out.println("Samp030");
System.out.println("Richard");
}//end constructor

public String toString(){


return "Baldwin";
}//end overridden toString()

//overloaded method
static void store(int dataIn){
classIntVar = dataIn;
}//end store

//overloaded method
static void store(double dataIn){
classDoubleVar = dataIn;
}//end store

static int fetchIntData(){


return classIntVar;
}//end fetchIntData

static double fetchDoubleData(){


return classDoubleVar;
}//end fetchDoubleData

//overloaded method
void setData(int dataIn){
instanceVar = dataIn;
}//end setData()

//overloaded method
void setData(Integer dataIn){
instanceVar = dataIn.intValue();
}//end setData()

int getData(){
return instanceVar;
}//end getData()
}//end class Samp030MyClass

Program Samp032.java

/*File Samp032
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Use of absolute value method of Math
class
Use of modulus operator to
distinguish between even and odd
values

The output consists of four lines of


text similar to the following. Note
however that random values are used
so the odd/even sequence may change
from one run to the next.

1728897982
Value is even
1728897983
Value is odd

**************************************/

import java.util.*;
class Samp032{
public static void main(
String[] args){
Random refToRNGen =
new Random(new Date().getTime());
int var = refToRNGen.nextInt();
System.out.println(Math.abs(var));
if(Math.abs(var)%2 == 0){
System.out.println(
"Value is even");
}else{
System.out.println(
"Value is odd");
}//end else

var++;//increment the value

System.out.println(Math.abs(var));
if(Math.abs(var)%2 == 0){
System.out.println(
"Value is even");
}else{
System.out.println(
"Value is odd");
}//end else
}//end main
}//end class Samp032

Program Samp034.java

/*File Samp034
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Behavior of default equals method
The this keyword

The output consists of the following


two lines of text:

true
false

**************************************/

import java.util.*;
class Samp034{
public static void main(
String[] args){
Samp034Class refVarA =
new Samp034Class(5);
Samp034Class refVarB =
new Samp034Class(5);

//Test object equal to itself.


System.out.println(
refVarA.equals(refVarA));

//Test object equal to another


// object of same class containing
// same data values
System.out.println(
refVarA.equals(refVarB));

}//end main
}//end class Samp034
//===================================//

class Samp034Class{
private int data;

Samp034Class(int data){//constructor
this.data = data;
}//end constructor

}//end class Samp034Class

Program Samp036.java

/*File Samp036
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Simple overridden equals method for
String data
The output consists of the following
three lines of text:

true
true
false

**************************************/

import java.util.*;
class Samp036{
public static void main(
String[] args){
Samp036Class refVarA =
new Samp036Class("Joe");
Samp036Class refVarB =
new Samp036Class("Joe");
Samp036Class refVarC =
new Samp036Class("Tom");

System.out.println(
refVarA.equals(refVarA) + " ");
System.out.println(
refVarA.equals(refVarB));
System.out.println(
refVarA.equals(refVarC));
}//end main
}//end class Samp036
//===================================//

class Samp036Class{
private String data;

//constructor
Samp036Class(String data){
this.data = data;
}//end constructor

public boolean equals(


Samp036Class objRefIn){
return this.data.equals(
objRefIn.data);
}//end overridden equals()

}//end class Samp036Class

Program Samp038.java

/*File Samp038
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win


Illustrates:
Counting number of objects
instantiated from same class
String concatenation

The output consists of the following


three lines of text:

1 Joe
2 Sue
3 Tom

Note, this is one of the small number


of valid uses for non-final class
variables.

**************************************/

import java.util.*;
class Samp038{
public static void main(
String[] args){
Samp038Class refVarA =
new Samp038Class("Joe");
Samp038Class refVarB =
new Samp038Class("Sue");
Samp038Class refVarC =
new Samp038Class("Tom");
}//end main
}//end class Samp038
//===================================//

class Samp038Class{
private String data;
private static int count = 0;

//constructor
Samp038Class(String data){
this.data = data;
System.out.println(
++count + " " + data);
}//end constructor

}//end class Samp038Class

Program Samp040.java

/*File Samp040
Copyright 2001, R.G.Baldwin
Rev 11/28/01

Tested using JDK 1.3 under Win

Illustrates:
Overridden equals() method
Class variable for counting object
instantiations

The output consists of the following


three lines of text. The order of
the words false and true is determined
by the value of a random number, and
may be different each time the program
is run.

Samp040
Richard Baldwin
false true

**************************************/

import java.util.*;
class Samp040{
public static void main(
String[] args){
Samp040Class refVarA =
new Samp040Class();
Samp040Class refVarB =
new Samp040Class();

Random refToRNGen =
new Random(new Date().getTime());

int var3 = refToRNGen.nextInt();


int var4 = refToRNGen.nextInt();
if(Math.abs(var4)%2 == 0){
//value is even
refVarA.setData(var3);
refVarB.setData(var3);
}else{
//value is odd
refVarA.setData(var3);
refVarB.setData(var3 + var4);
}//end else
System.out.print(
refVarA.equals(refVarB) + " ");

if(Math.abs(var4)%2 != 0){
//value is odd
refVarA.setData(var3);
refVarB.setData(var3);
}else{
//value is even
refVarA.setData(var3);
refVarB.setData(var3 + var4);
}//end else
System.out.println(
refVarB.equals(refVarA));

}//end main
}//end class Samp040
//===================================//

class Samp040Class{
private static int objCnt = 0;
private int data;

Samp040Class(){//constructor
if(objCnt++ == 0){
//Display name only for first
// object instantiated
System.out.println("Samp040");
System.out.println(
"Richard Baldwin");}
}//end constructor

void setData(int dataIn){


data = dataIn;
}//end setData()

public boolean equals(


Samp040Class objRefIn){
return data == objRefIn.data;
}//end overridden equals()

}//end class Samp040Class

Program Samp048.java

/*File Samp048
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiating an abstract class is
not allowed.
Extending an abstract class.
Parameterized constructor.
Storing a ref to a subclass object in
a ref var of a superclass type.
Requirement to downcast a superclass
ref variable to access a method in
a subclass object.
Overridden toString method.
The this keyword.

The output consists of the following


five lines of text. Because the
program generates a random data value
for testing, the actual values
displayed will differ from one run to
the next.
Samp048
Richard
Baldwin
23
23

**************************************/
import java.util.*;

//Note that this class is abstract


abstract class Samp048{
public static void main(
String[] args){

//Following statement will not


// compile. Cannot instantiate an
// abstract class
// Samp048 refVar = new Samp048();

Random rGen = new Random(


new Date().getTime());
int ranNo = (byte)rGen.nextInt();

//Note the superclass ref variable


// type and the subclass object
Samp048 refVar =
new Samp048Class(ranNo);
System.out.println(refVar);

//Note the following required cast


System.out.println(
((Samp048Class)refVar).
getData());
System.out.println(ranNo);
}//end main

}//end class Samp048


//===================================//

class Samp048Class extends Samp048{


private int data;

//constructor
Samp048Class(int data){
System.out.println("Samp048");
System.out.println("Richard");
this.data = data;
}//end constructor

public int getData(){


return data;
}//end getData()

//overridden method - defined in the


// Object class
public String toString(){
return "Baldwin";
}//end overloaded toString()

}//end class Samp048Class

Program Samp050.java

/*File Samp050
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Extending an abstract class.
Parameterized constructor.
Defining an abstract method in the
superclass and overriding it in a
subclass to make it accessible
without a requirement to downcast
to the subclass type.
Overridden toString method.

The output consists of the following


five lines of text. Because the
program generates a random data value
for testing, the actual values
displayed will differ from one run to
the next.

Samp050
Richard
Baldwin
23
23

**************************************/
import java.util.*;

//Note that this class is abstract


abstract class Samp050{
public static void main(
String[] args){
Random rGen = new Random(
new Date().getTime());
int ranNo = (byte)rGen.nextInt();

//Note the superclass ref variable


// type and the subclass object
Samp050 refVar =
new Samp050Class(ranNo);
System.out.println(refVar);
System.out.println(
refVar.getData());
System.out.println(ranNo);
}//end main

//Note the following abstract method


// that is overridden in the subclass
public abstract int getData();

}//end class Samp050


//===================================//

class Samp050Class extends Samp050{


private int data;

//constructor
Samp050Class(int inData){
System.out.println("Samp050");
System.out.println("Richard");
data = inData;
}//end constructor

//overridden method - abstract in the


// supeclass
public int getData(){
return data;
}//end getData()

//overridden method - defined in the


// Object class
public String toString(){
return "Baldwin";
}//end overloaded toString()

}//end class Samp050Class

Program Samp056.java

/*File Samp056
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Downcasting object ref in order to
access a method belonging to the
object.

The output consists of the following


two lines of text.

Samp056
Hello from Baldwin
**************************************/

import java.util.*;
class Samp056{
public static void main(
String[] args){

//Store ref to subclass object in


// ref var of superclass type
Samp056 var =
new Samp056Class("Baldwin");

//Following statement won't compile


// var.sayHello();

//Downcast the superclass ref to


// the subclass type to invoke the
// method.
((Samp056Class)var).sayHello();

}//end main
}//end class Samp056
//===================================//

class Samp056Class extends Samp056{


private String data;

Samp056Class(String data){
System.out.println("Samp056");
this.data = data;
}//end constructor

public void sayHello(){


System.out.println(
"Hello from " + data);
}//end sayHello()

}//end class Samp056Class

Program Samp058.java

/*File Samp058
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiating anonymous object, and
invoking method on that object.

The output consists of the following


two lines of text.
Samp058
Hello from Baldwin

**************************************/

import java.util.*;
class Samp058{
public static void main(
String[] args){
//Instantiate anonymous object and
// invoke method on that object.
new Samp058Class("Baldwin").
sayHello();

}//end main
}//end class Samp058
//===================================//

class Samp058Class{
private String data;

Samp058Class(String data){
System.out.println("Samp058");
this.data = data;
}//end constructor

public void sayHello(){


System.out.println(
"Hello from " + data);
}//end sayHello()

}//end class Samp058Class

Program Samp060.java

/*File Samp060
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiating anonymous object, and
invoking method on that object.
Extending a class,
Passing subclass object reference as
superclass type.
Downcasting incoming object ref to
access method.

The output consists of the following


five lines of text. Because the
program generates a random data value
for testing, the actual values
displayed will differ from one run to
the next.

Samp060
Richard
Baldwin
78
78

**************************************/

import java.util.*;
class Samp060{
public static void main(
String[] args){

Random rGen = new Random(


new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Note the following superclass


// ref var holding ref to subclass
// object.
Samp060 objRef =
new Samp060ClassA(rNum);

//Instantiate anonymous object,


// invoke method on anonymous
// object passing superclass ref
// var as parameter.
System.out.println(
new Samp060ClassB().
getFromOtherObj(objRef));

System.out.println(rNum);

}//end main
}//end class Samp060
//===================================//

class Samp060ClassA extends Samp060{


private int data;

Samp060ClassA(int data){
System.out.println("Samp060");
System.out.println("Richard");
this.data = data;
}//end constructor

public int getData(){


return data;
}//end getData()

}//end class Samp060ClassA


//===================================//
class Samp060ClassB{

Samp060ClassB(){
System.out.println("Baldwin");
}//end constructor

public int getFromOtherObj(


Samp060 refToObj){
//Note the required cast
return ((Samp060ClassA)refToObj).
getData();
}//end getFromOtherObj()

}//end class Samp060ClassB

Program Samp066.java

/*File Samp066
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Create and populate an array object
without use of keyword new.

The output consists of the following


two lines of text:

1 2 3
Richard Baldwin

**************************************/

class Samp066{
public static void main(
String[] args){

//Create and populate array object


// of type int without use of
// keyword new.
int[] intArrayRef = {1,2,3};

//Display contents of array


// elements
for(int cnt=0;
cnt<intArrayRef.length;
cnt++){
System.out.print(
intArrayRef[cnt] + " ");
}//end for loop
System.out.println();
//Create and populate array object
// of type Samp066Class without
// use of keyword new.
Samp066Class[] objArrayRef = {
new Samp066Class("Richard"),
new Samp066Class("Baldwin")};

//Display contents of array


// elements
for(int cnt=0;
cnt<objArrayRef.length;
cnt++){
System.out.print(
objArrayRef[cnt].getData()
+ " ");
}//end for loop
System.out.println();

}//end main
}//end class Samp066
//===================================//

class Samp066Class{
private String data;

Samp066Class(String data){
this.data = data;
}//end constructor

public String getData(){


return data;
}//end getData()

}//end class Samp066Class

Program Samp068.java

/*File Samp068
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Create and populate an array object
of type Object without use of
keyword new.
Downcast object references when
fetched from array to access
method.

The output consists of the following


line of text:
Richard Baldwin

**************************************/

class Samp068{
public static void main(
String[] args){

//Create and populate array object


// of type Object without use of
// keyword new.
Object[] objArrayRef = {
new Samp068Class("Richard"),
new Samp068Class("Baldwin")};

//Display contents of objects


// referred to by array elements
for(int cnt=0;
cnt<objArrayRef.length;
cnt++){
//Following won't compile due to
// need for downcast
// System.out.print(
// objArrayRef[cnt].getData()
// + " ");
System.out.print(((Samp068Class)
objArrayRef[cnt]).getData()
+ " ");

}//end for loop


System.out.println();

}//end main
}//end class Samp068
//===================================//

class Samp068Class{
private String data;

Samp068Class(String data){
this.data = data;
}//end constructor

public String getData(){


return data;
}//end getData()

}//end class Samp068Class

Program Samp070.java

/*File Samp070
Copyright 2001, R.G.Baldwin
Rev 11/29/01

Tested using JDK 1.3 under Win

Illustrates:
Create one-element array of type
Object without use of keyword new.
Populate array element with reference
to object when array is created.
Passing object reference as type
Object.
Downcasting incoming object ref to
access method.

The output consists of the following


five lines of text. Because the
program generates a random data value
for testing, the actual values
displayed will differ from one run to
the next.

Samp070
Richard
Baldwin
78
78

**************************************/

import java.util.*;
class Samp070{
public static void main(
String[] args){

Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Create and populate one-element


// array object without use of
// keyword new.
Object[] objRef =
{new Samp070ClassA(rNum)};

//Create anonymous object and


// invoke method on it, passing
// parameter as type Object.
System.out.println(
new Samp070ClassB().
getFromOtherObj(objRef[0]));

System.out.println(rNum);

}//end main
}//end class Samp070
//===================================//

class Samp070ClassA extends Samp070{


private int data;

Samp070ClassA(int data){
System.out.println("Samp070");
System.out.println("Richard");
this.data = data;
}//end constructor

public int getData(){


return data;
}//end getData()

}//end class Samp070ClassA


//===================================//

class Samp070ClassB{

Samp070ClassB(){
System.out.println("Baldwin");
}//end constructor

//Note that incoming parameter is


// type Object.
public int getFromOtherObj(
Object refToObj){

//Downcast to get and return data


// from another object.
return ((Samp070ClassA)refToObj).
getData();
}//end getFromOtherObj()

}//end class Samp070ClassB

Copyright 2001, Richard G. Baldwin. Reproduction in whole or in part in any form or


medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX)
and private consultant whose primary focus is a combination of Java and XML. In
addition to the many platform-independent benefits of Java applications, he believes that
a combination of Java and XML will become the primary driving force in the delivery of
structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a


combination of the two. He frequently provides onsite Java and/or XML training at the
high-tech companies located in and around Austin, Texas. He is the author of Baldwin's
Java Programming Tutorials, which has gained a worldwide following among
experienced and aspiring Java programmers. He has also published articles on Java
Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years
of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-

Introduction to Object-Oriented Programming, Sample


Programs, Set 2
Published: December 1, 2001
By Richard G. Baldwin

Java Programming Tutorial # 9001

• Preface
• Sample Programs
• About the Author

Preface
This is the second in a miniseries of lessons designed specifically to help the students in
my "Introduction to Object-Oriented Programming" course study for their exams.
However, others may find the lesson useful as well.

The lesson consists of a set of simple programs, each designed to illustrate one or more
important Java OOP concepts. The concepts involved are identified in the comments at
the beginning of each program.

The programs are designed to illustrate the code without providing a detailed discussion
of the code. You are referred to the other lessons in my online Java tutorials for detailed
discussions of the OOP concepts illustrated by these programs.

Sample Programs
Program Samp076.java

/*File Samp076
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Interface definitions,
Implementing one or more interfaces
in class definition,
Defining interface methods in class
definition,
Casting from one interface type
to another.

The output consists of the following


five lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. However, in
all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.

Samp076
Richard
Baldwin
-64 -63 -62
-63 -63 -63

**************************************/

import java.util.*;

class Samp076{
public static void main(
String[] args){

Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Store refs to objs in ref vars of


// interface types
Samp076IntfcA var1 =
new Samp076ClassA(rNum);
Samp076IntfcB var2 =
new Samp076ClassB(rNum);
//Invoke interface method on refs
// to objects. Note that
// implementations of interface
// method differ. Note rqmt for
// cast.
System.out.print(
var1.getModifiedData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp076IntfcA)var2).
getModifiedData());

//Invoke interface method on refs


// to objects. Note that
// implementations of interface
// method are the same. Note rqmt
// for cast.
System.out.print(
((Samp076IntfcB)var1).
getData() + " ");
System.out.print(rNum + " ");
System.out.println(
var2.getData());
}//end main
}//end class Samp076
//===================================//

interface Samp076IntfcA{
public int getModifiedData();
}//end interface
//===================================//

interface Samp076IntfcB{
public int getData();
}//end interface
//===================================//

class Samp076ClassA
implements Samp076IntfcA,
Samp076IntfcB{
private int data;

Samp076ClassA(int data){
System.out.println("Samp076");
System.out.println("Richard");
this.data = data;
}//end constructor

//Define interface method


public int getModifiedData(){
return data - 1;
}//end getModifiedData()

//Define interface method


public int getData(){
return data;
}//end getData()

}//end class Samp076ClassA


//===================================//

class Samp076ClassB
implements Samp076IntfcA,
Samp076IntfcB{
private int data;

Samp076ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor

//Define interface method


public int getModifiedData(){
return data + 1;
}//end getModifiedData()

//Define interface method


public int getData(){
return data;
}//end getData()

}//end class Samp076ClassB

Program Samp078.java

/*File Samp078
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the getClass method of the
Object class,
Use of the forName method of the
Class class,
Use of the getInterfaces method of
the Class class,
Use of the getSuperclass method of
the Class class,

The output consists of the following


lines of text. Because the program
generates random data for testing, the
numeric values will differ from one run
to the next. However, the two values
will be the same.

Note that a space was manually inserted


near the end to force the material to
fit in this narrow format.

Samp078
Richard Baldwin
74 74
Samp078ClassA
class java.lang.Object
interface Samp078IntfcA
interface Samp078IntfcB

java.awt.Button
class java.awt.Component
interface javax.accessibility.
Accessible

**************************************/

import java.util.*;
import java.awt.*;

class Samp078{
public static void main(
String[] args){

Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Store ref to obj in ref var of


// interface type
Samp078IntfcB var1 =
new Samp078ClassA(rNum);

//Invoke interface method on ref


// to object.
System.out.print(
var1.getData() + " ");
System.out.println(rNum + " ");

//Get Class obj representing target


// class based on ref to object.
Class var2 = var1.getClass();

//Get and display name of target


// class and name of superclass
// of target class
System.out.println(var2.getName());
System.out.println(
var2.getSuperclass());

//Get and display list of


// interfaces implemented by the
// target class.
Class[] var3 =
var2.getInterfaces();
for(int cnt=0; cnt<var3.length;
cnt++){
System.out.println(var3[cnt]);
}//end for loop
System.out.println();

//Get Class obj representing target


// class based on class name
// as string.
try{
var2 = Class.forName(
"java.awt.Button");

//Get and display name of target


// class and name of superclass
// of target class
System.out.println(
var2.getName());
System.out.println(
var2.getSuperclass());

//Get and display list of


// interfaces implemented by the
// target class.
var3 = var2.getInterfaces();
for(int cnt=0; cnt<var3.length;
cnt++){
System.out.println(var3[cnt]);
}//end for loop
}catch(ClassNotFoundException e){
System.out.println("Error");
}//end catch block

}//end main
}//end class Samp078
//===================================//

interface Samp078IntfcA{
public void intfcMethod();
}//end interface
//===================================//

interface Samp078IntfcB{
public int getData();
}//end interface
//===================================//

class Samp078ClassA
implements Samp078IntfcA,
Samp078IntfcB{
private int data;

Samp078ClassA(int data){
System.out.println("Samp078");
System.out.println(
"Richard Baldwin");
this.data = data;
}//end constructor

//Define interface method as empty


// method
public void intfcMethod(){
//empty method
}//end intfcMethod()

//Define interface method


public int getData(){
return data;
}//end getData()

}//end class Samp078ClassA


//===================================//

Program Samp080.java

/*File Samp080
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Interface definitions,
Implementing one or more interfaces
in class definition,
Defining interface methods in class
definition,
Overridden toString method,
Use of the getClass method of the
Object class,
Use of the getInterfaces method of
the Class class

The output consists of the following


nine lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. However, in
all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.
3. All three values in the third row
of numbers will be algebraically five
greater than the values in the second
row of numbers.

Samp080
Richard
Baldwin
-109 -108 -107
-108 -108 -108
-103 -103 -103
interface Samp080IntfcA
interface Samp080IntfcA
interface Samp080IntfcB

**************************************/

import java.util.*;

class Samp080{
public static void main(
String[] args){

Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Store ref to obj in ref var of


// interface type
Samp080IntfcA var1 =
new Samp080ClassA(rNum);
Samp080IntfcA var2 =
new Samp080ClassB(rNum);

//Invoke interface method on refs


// to objects. Note that
// implementations of interface
// method differ.
System.out.print(
var1.getModifiedData() + " ");
System.out.print(rNum + " ");
System.out.println(
var2.getModifiedData());

//Invoke interface method on refs


// to objects. Note that
// implementations of interface
// method are the same.
System.out.print(
var1.getData() + " ");
System.out.print(rNum + " ");
System.out.println(var2.getData());

//Invoke overridden toString method


// on refs to objects. Note that
// overridden versions are the
// same.
System.out.print(var1 + " ");
System.out.print(rNum + 5 + " ");
System.out.println(var2);

//Get Class obj representing one


// class.
Class var3 = var1.getClass();
//Get and display list of
// interfaces implemented by the
// target class.
Class[] var4 =
var3.getInterfaces();
for(int cnt=0; cnt<var4.length;
cnt++){
System.out.println(var4[cnt]);
}//end for loop

//Get Class obj and do same for


// the other class.
Class var5 = var2.getClass();
Class[] var6 =
var5.getInterfaces();
for(int cnt=0; cnt<var6.length;
cnt++){
System.out.println(var6[cnt]);
}//end for loop
}//end main
}//end class Samp080
//===================================//

interface Samp080IntfcA{
public int getModifiedData();
public int getData();
}//end interface
//===================================//

interface Samp080IntfcB{
//this is a dummy interface
}//end interface
//===================================//

class Samp080ClassA
implements Samp080IntfcA{
private int data;

Samp080ClassA(int data){
System.out.println("Samp080");
System.out.println("Richard");
this.data = data;
}//end constructor

//Define interface method


public int getModifiedData(){
return data - 1;
}//end getModifiedData()

//Define interface method


public int getData(){
return data;
}//end getData()

//Override toString method


public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp080ClassA
//===================================//

class Samp080ClassB
implements Samp080IntfcA,
Samp080IntfcB{
private int data;

Samp080ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor

//Define interface method


public int getModifiedData(){
return data + 1;
}//end getModifiedData()

//Define interface method


public int getData(){
return data;
}//end getData()

//Override tostring method


public String toString(){
return "" + (data + 5);
}//end toString()
}//end class Samp080ClassB

Program Samp088.java

/*File Samp088
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Saving object ref as class type,
interface type, or type Object,
Casting ref stored as type Object
to class type or interface type
to access interface method,
Accessing overridden toString
method on references of all three
types without a requirement to
perform a cast.

The output consists of the following


five lines of text.

intfcMethod output
intfcMethod output
Overridden toString output
Overridden toString output
Overridden toString output

**************************************/

import java.util.*;

class Samp088{
public static void main(
String[] args){
String strData = "";//for use later

Samp088Class var1 =
new Samp088Class();
Samp088Intfc var2 = var1;
Object var3 = var1;

var1.intfcMethod();
var2.intfcMethod();
//Following will not compile due
// to need for a cast
// strData = var3.intfcMethod();

//Either of the following casts


// will resolve the above problem
strData = ((Samp088Class)var3).
intfcMethod();
System.out.println(strData);

strData = ((Samp088Intfc)var3).
intfcMethod();
System.out.println(strData);

//No cast is required to invoke


// overridden toString method
// for ref stored as class type,
// interface type, or type Object
strData = var1.toString();
System.out.println(strData);
strData = var2.toString();
System.out.println(strData);
strData = var3.toString();
System.out.println(strData);
}//end main
}//end class Samp088
//===================================//

interface Samp088Intfc{
public String intfcMethod();
}//end interface
//===================================//

class Samp088Class
implements Samp088Intfc{

//define interface method


public String intfcMethod(){
return "intfcMethod output";
}//end getData()

//override toString method


public String toString(){
return
"Overridden toString output";
}//end toString()
}//end class Samp088Class

Program Samp090.java

/*File Samp090
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Interface definitions,
Implementing an interface in class
definition,
Defining interface methods in class
definition,
Storing references to new objects in
elements of an array of type
Object,
Cast elements to interface type in
order to invoke methods,
Overridden toString method.

The output consists of the following


six lines of text. Because the program
generates random data for testing, the
actual values will differ from one run
to the next. However, in all cases:
1. The values in the first row of
numbers will be a sequence of
consecutive integers in increasing
algebraic order from left to right.
2. All three values in the second row
of numbers will match the value of the
center number in the first row of
numbers.
3. All three values in the third row
of numbers will be algebraically five
greater than the values in the second
row of numbers.

Samp090
Richard
Baldwin
-68 -67 -66
-67 -67 -67
-62 -62 -62

**************************************/

import java.util.*;

class Samp090{
public static void main(
String[] args){

Random rGen =
new Random(new Date().getTime());
int rNum = (byte)rGen.nextInt();

//Create a two-element array


// object of type Object
Object[] var1 = new Object[2];

//Store refs to two new objects


// in the array as type Object
var1[0] = new Samp090ClassA(rNum);
var1[1] = new Samp090ClassB(rNum);

//Cast contents of array elements


// to interface type and invoke
// interface methods on them
System.out.print(
((Samp090Intfc)var1[0]).
getModData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp090Intfc)var1[1]).
getModData());

//Do the same and invoke the


// other interface method
System.out.print(
((Samp090Intfc)var1[0]).
getData() + " ");
System.out.print(rNum + " ");
System.out.println(
((Samp090Intfc)var1[1]).
getData());

//Are the following two casts


// required?
System.out.print(
((Samp090Intfc)var1[0]) + " ");
System.out.print(rNum + 5 + " ");
System.out.println(
((Samp090Intfc)var1[1]));
//The two casts above are not
// required. The print method
// invokes the toString method,
// which is not an interface
// method. Rather, it is
// inherited from the class named
// Object and overridden in the
// class named Samp090ClassA.
// However, it is important to
// note that methods inherited
// from the Object class can be
// invoked on references of
// interface types.

}//end main
}//end class Samp090
//===================================//

interface Samp090Intfc{
public int getModData();
public int getData();
}//end interface
//===================================//

class Samp090ClassA
implements Samp090Intfc{
private int data;

Samp090ClassA(int data){
System.out.println("Samp090");
System.out.println("Richard");
this.data = data;
}//end constructor

public int getModData(){


return data - 1;
}//end getModData()

public int getData(){


return data;
}//end getData()

public String toString(){


return "" + (data + 5);
}//end toString()
}//end class Samp090ClassA
//===================================//

class Samp090ClassB
implements Samp090Intfc{
private int data;
Samp090ClassB(int data){
System.out.println("Baldwin");
this.data = data;
}//end constructor

public int getModData(){


return data + 1;
}//end getModData()

public int getData(){


return data;
}//end getData()

public String toString(){


return "" + (data + 5);
}//end toString()
}//end class Samp090ClassB

Program Samp098.java

/*File Samp098
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the Collection Framework, the
List interface, and the ArrayList
class. The ArrayList class implements
the List interface. The add method of
the List interface allows duplicates.

The ArrayList class does not implement


an interface that requires it to
maintain the collections in sorted
order.

Therefore, adding object references


to an object instantiated from a class
that implements List results in a
Collection object that maintains the
collection in the same order that the
items were added, allowing duplicates.
(New items can be added at the end
or inserted anywhere in the list.
However, in order to insert, it is
necessary to treat the reference as
type List or ArrayList and not as type
Collection.)

Note that List is a subinterface of


Collection. Therefore, a class that
implements List also implements
Collection. A reference to an object
of that class can be stored as type
List or type Collection.

This program also illustrates the use


of the Iterator interface for the
purpose of traversing a collection.

The output of this program is as


follows:

Depending on whether the value of rNum


is odd or even, the output consists of
one of the following groups of four
lines of text. Because the program
generates the data on the basis of a
random value, the output will differ
from one run to the next. However, in
all cases, the output will match one of
the groups of four lines of text shown
below.

Samp098
Richard Baldwin
Harry is first
Harry Joe Bill Sue Tom Bill

Samp098
Richard Baldwin
Mike is first
Mike Bill Tom Mary Mike Alice

**************************************/
import java.util.*;
class Samp098{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;

//Instantiate a new object of a


// class that extends ArrayList and
// store its reference as the
// interface type Collection
Collection var =
new Samp098Class();

//Invoke the add method on the


// object six times in succession
// to add sex new items to the
// collection. Note that they are
// not added in order. Note also
// that there are duplicates.
if(rNum == 0){
System.out.println(
"Harry is first");
var.add("Joe");
var.add("Bill");
var.add("Sue");
var.add("Tom");
var.add("Bill");
//Insert at index 0. Note the
// required cast.
((List)var).add(0,"Harry");
}else{
System.out.println(
"Mike is first");
var.add("Mike");
var.add("Bill");
var.add("Mary");
var.add("Mike");
var.add("Alice");
//Insert at index 2. Note the
// required cast.
((List)var).add(2,"Tom");
}//end else

//Invoke the iterator method on the


// reference to the Collection
// object to get a reference to an
// object of the interface type
// Iterator.
Iterator iter = var.iterator();

//Use the Iterator object to access


// and display all of the items
// in the Collection object.
while(iter.hasNext()){
System.out.print(
iter.next() + " ");
}//end while loop
System.out.println();
}//end main
}//end class Samp098
//===================================//

class Samp098Class extends ArrayList{


//Other than a constructor to display
// the programmer's name and the
// program name, this class doesn't
// require a body. It inherits
// everything needed from ArrayList.
// Therefore, this class is a
// ArrayList class with a special
// constructor.

Samp098Class(){//constructor
System.out.println("Samp098");
System.out.println(
"Richard Baldwin");
}//end constructor
}//end class Samp098Class

Program Samp100.java

/*File Samp100
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the Collection Framework, the
Set interface, and the TreeSet class.
The TreeSet class implements the Set
interface. The add method of the Set
interface doesn't allow duplicates.

The TreeSet class also implements the


SortedSet interface. Classes that
implement the SortedSet interface
maintain their collections in sorted
order.

Therefore, adding object references


to an object instantiated from a class
that implements both Set and SortedSet
results in a Collection object that
maintains the collection in sorted
order without any duplicates.

Note that both Set and SortedSet are


subinterfaces of Collection.
Therefore, a class that implements
either Set or SortedSet also
implements Collection. A reference to
an object of that class can be stored
as Set, SortedSet, or Collection.

This program also illustrates the use


of the Iterator interface for the
purpose of traversing a collection.

The output of this program is as


follows:

Depending on whether the value of rNum


is odd or even, the output consists of
one of the following groups of four
lines of text. Because the program
generates the data on the basis of a
random value, the output will differ
from one run to the next. However, in
all cases, the output will match one of
the groups of four lines of text shown
below.

Samp100
Richard Baldwin
Bill is first
Bill Joe Sue Tom

Samp100
Richard Baldwin
Alice is first
Alice Bill Mary Mike

**************************************/
import java.util.*;
class Samp100{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;

//Instantiate a new object of a


// class that extends TreeSet and
// store its reference as the
// interface type Collection
Collection var =
new Samp100Class();

//Invoke the add method on the


// object five times in succession
// to add five new items to the
// collection. Note that they are
// not added in order. Note also
// that there are duplicates.
if(rNum == 0){
System.out.println(
"Bill is first");
var.add("Joe");
var.add("Bill");
var.add("Sue");
var.add("Tom");
var.add("Bill");
}else{
System.out.println(
"Alice is first");
var.add("Mike");
var.add("Bill");
var.add("Mary");
var.add("Mike");
var.add("Alice");
}//end else

//Invoke the iterator method on the


// reference to the Collection
// object to get a reference to an
// object of the interface type
// Iterator.
Iterator iter = var.iterator();

//Use the Iterator object to access


// and display all of the items
// in the Collection object. Note
// that they will be accessed in
// sorted order with duplicates
// removed.
while(iter.hasNext()){
System.out.print(
iter.next() + " ");
}//end while loop
System.out.println();
}//end main
}//end class Samp100
//===================================//

class Samp100Class extends TreeSet{


//Other than a constructor to display
// the programmer's name and the
// program name, this class doesn't
// require a body. It inherits
// everything needed from TreeSet.
// Therefore, this class is a TreeSet
// class with a special constructor.

Samp100Class(){//constructor
System.out.println("Samp100");
System.out.println(
"Richard Baldwin");
}//end constructor
}//end class Samp100Class

Program Samp106.java

/*File Samp106
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the binarySearch method of the
Arrays class. This is a simple program
for students who dig deeply enough into
the Sun documentation to learn how to
use the binarySearch method of the
Arrays class. Otherwise, it will be a
fairly difficult problem.

The program searches a sorted array of


Strings to find and return the index
of a key String. If the String is not
in the array, a negative index value
is returned.

The output consists of the following


five lines of text:

Samp106
Richard Baldwin
Dick Harry Tom
Harry is at index 1
Bill is not in array

**************************************/
import java.util.*;
class Samp106{
public static void main(
String[] args){
System.out.println(
Samp106Class.displayName());

//Create an array object of type


// Object. Populate it with refs
// to String objects.
Object[] arrayRef = {
"Tom","Dick","Harry"};

//Sort the array


Arrays.sort(arrayRef);

//Display the contents of the


// sorted array
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();

//Search the array for a key string


String key = "Harry";
int index = Samp106Class.
searchArray(arrayRef,key);

//Display location of key string


Samp106Class.indexHandler(
index,key);

//Search the array for a key string


// that doesn't exist in the array
key = "Bill";
index = Samp106Class.searchArray(
arrayRef,key);

//Display location of key string


Samp106Class.indexHandler(
index,key);

}//end main

}//end class Samp106


//===================================//

class Samp106Class{
static String displayName(){
System.out.println("Samp106");
return "Richard Baldwin";
}//end displayName()

static int searchArray(


Object[] array, Object key){
return Arrays.binarySearch(
array,key);
}//end searchArray

//Following method displays result


// of the search
static void indexHandler(
int index, String key){
if(index >= 0){
System.out.println(key +
" is at index " + index );
}else{
System.out.println(key +
" is not in array");
}//end else
}//end index handler

}//end class Samp106Class

Program Samp108.java

/*File Samp108
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the asList method of the Arrays
class. This is a simple program for
students who dig deeply enough into the
Sun documentation to learn how to use
the asList() method of the Arrays
class. Otherwise, it will be a very
difficult problem.

The program gets a List view on an


array, modifies the List view, and
demonstrates that changes made to the
List write through to the underlying
array.

The output consists of the following


four lines of text:

Samp108
Richard Baldwin
Tom Dick Harry
Tom TOM Dick DICK Harry HARRY

**************************************/
import java.util.*;
class Samp108{
public static void main(
String[] args){
System.out.println(
Samp108Class.displayName());

//Create an array object of type


// Object. Populate it with refs
// to String objects.
Object[] arrayRef = {
"Tom","Dick","Harry"};

//Display the contents of the


// String object referred to by the
// elements of the array object
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();

//Get a List view of the array


// object
List listRef =
Samp108Class.getListView(
arrayRef);
//Get a ListIterator on the List
ListIterator iter =
listRef.listIterator();
//Use the ListIterator to modify
// the contents of the elements in
// the List
while(iter.hasNext()){
Object ref = iter.next();
//Note the required cast
iter.set(ref + " " +
((String)ref).toUpperCase());
}//end while

//Display the contents of the


// array. Note that the changes
// to the List have "written
// through" to the underlying
// array.
for(int cnt=0;cnt<arrayRef.length;
cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
}//end main
}//end class Samp108
//===================================//

class Samp108Class{
static String displayName(){
System.out.println("Samp108");
return "Richard Baldwin";
}//end displayName()

static List getListView(


Object[] array){
return Arrays.asList(array);
}//end getListView

}//end class Samp108Class

Program Samp110.java

/*File Samp110
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Sorting strings in an array.

This is a very easy program for the


student who takes the time to dig
into the documentation and discover
the sort() method of the Arrays class.
It will be more difficult for students
who doesn't do that and attempt to
write their own sort routine.

The output of this program is as


follows:

Depending on whether the value of rNum


is odd or even, the output consists of
one of the following groups of four
lines of text. Because the program
generates the data on the basis of a
random value, the output will differ
from one run to the next. However, in
all cases, the output will match one of
the groups of four lines of text shown
below.

Bill is first
Samp110
Richard Baldwin
Bill Bill Joe Tom sue

Alice is first
Samp110
Richard Baldwin
Alice Bill Mike Mike mary

**************************************/
import java.util.*;
class Samp110{
public static void main(
String[] args){
Random rGen =
new Random(new Date().getTime());
int rNum = rGen.nextInt()%2;

String[] arrayRef = new String[5];


if(rNum == 0){
System.out.println(
"Bill is first");
arrayRef[0]="Joe";
arrayRef[1]="Bill";
arrayRef[2]="sue";
arrayRef[3]="Tom";
arrayRef[4]="Bill";
}else{
System.out.println(
"Alice is first");
arrayRef[0]="Mike";
arrayRef[1]="Bill";
arrayRef[2]="mary";
arrayRef[3]="Mike";
arrayRef[4]="Alice";
}//end else

Prob04Class.showYourName();
Prob04Class.sortArray(arrayRef);

for(int cnt=0;
cnt < arrayRef.length; cnt++){
System.out.print(
arrayRef[cnt] + " ");
}//end for loop
System.out.println();
}//end main

}//end class Exam1Prob04


//===================================//
class Prob04Class{
static void showYourName(){
System.out.println("Samp110");
System.out.println(
"Richard Baldwin");
}//end showYourName()

static void sortArray(


String[] arrayRef){
Arrays.sort(arrayRef);
}//end sortArray()
}//end class Prob04Class

Program Samp116.java

/*File Samp116
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of array objects containing
refs to other array objects,
The ability to copy data from one
array object to another,

The output consists of the following


seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.

Samp116
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119

**************************************/

import java.util.*;
public class Samp116 {
public static void main(
String[] args){
Samp116Class.displayYourName();
Random rGen =
new Random(new Date().getTime());

//Generate four random numbers and


// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");

//Create two array objects of type


// int[], each containing two
// elements.
int[] refToIntArrayA = new int[2];
int[] refToIntArrayB = new int[2];

//Copy two values from the rawData


// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);

//Create a two-element array of


// type int[][]. Populate each
// element with a reference to one
// of the two-element int arrays
// created and populated earlier.
int[][] refTo2dArray =
{refToIntArrayA,refToIntArrayB};

//Invoke a method that will


// display the values stored in
// each of the two-element int
// arrays whose references are
// stored in the two-element array
// of type int[][].
Samp116Class.displayArrayData(
refTo2dArray);
}//end main
}//end class Samp116
//===================================//

class Samp116Class{
public static void displayYourName(){
System.out.println("Samp116");
System.out.println(
"Richard Baldwin");
}//end displayYourName()

public static void displayArrayData(


int[][] refTo2dArray){
for(int j = 0;
j<refTo2dArray.length;j++){
for(int i=0;
i<refTo2dArray[j].length;i++){
System.out.print(
refTo2dArray[j][i] + " ");
}//end inner for loop
System.out.println();
}//end outer for loop
}//end displayArrayData()
}//end class Samp116Class

Program Samp118.java

/*File Samp118
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the generic type Object to
store a reference to an array
object,
The requirement to cast from Object
to int[] to access the data in the
array object stored as type Object.

The output consists of the following


seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.

Samp118
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119

**************************************/
import java.util.*;
public class Samp118 {
public static void main(
String[] args){
Samp118Class.displayYourName();
Random rGen =
new Random(new Date().getTime());

//Generate four random numbers and


// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");

//Create two array objects of type


// int[], each containing two
// elements. Save refs to the
// array objects in ref vars of
// type Object. Note that these
// ref vars are not declared as
// type Object[].
Object refToIntArrayA = new int[2];
Object refToIntArrayB = new int[2];

//Copy two values from the rawData


// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);

//Invoke a method that will


// display the values stored in
// one of the two-element int
// arrays whose reference is
// stored in a ref var of the
// type Object.
Samp118Class.displayArrayData(
refToIntArrayA);
//Do it again to display the other
// array.
Samp118Class.displayArrayData(
refToIntArrayB);
}//end main
}//end class Samp118
//===================================//

class Samp118Class{
public static void displayYourName(){
System.out.println("Samp118");
System.out.println(
"Richard Baldwin");
}//end displayYourName()

public static void displayArrayData(


Object refTypeObject){
//Note the following two rqmts to
// cast from type Object to
// type int[].
for(int j = 0;
j<((int[])refTypeObject).length;
j++){
System.out.print(
((int[])refTypeObject)[j]
+ " ");
}//for loop
System.out.println();
}//end displayArrayData()
}//end class Samp118Class

Program Samp120.java

/*File Samp120
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of array objects containing
refs to other array objects,
The ability to copy data from one
array object to another,
The use of the generic type Object to
store a reference to an array
object,
The requirement to cast from Object
to int[] to access the data in the
array object stored as type Object.

The output consists of the following


seven lines of text. Because the
program generates random data for
testing, the actual values will differ
from one run to the next. In all cases,
the four values and the arrangement of
those four values above the broken line
will match the four values and the
arrangement of the four values below
the broken line.

Samp120
Richard Baldwin
45 4
-17 -119
-------
45 4
-17 -119

**************************************/

import java.util.*;
public class Samp120 {
public static void main(
String[] args){
Samp120Class.displayYourName();
Random rGen =
new Random(new Date().getTime());

//Generate four random numbers and


// save them in a four-element
// array object of type int.
int[] rawData = new int[4];
for(int cnt=0;cnt<rawData.length;
cnt++){
rawData[cnt] =
(byte)rGen.nextInt();
System.out.print(
rawData[cnt] + " ");
if(cnt==1)System.out.println();
}//end for loop
System.out.println();
System.out.println("-------");

//Create two array objects of type


// int[], each containing two
// elements. Save refs to the
// array objects in ref vars of
// type Object. Note that these
// ref vars are not declared as
// type Object[].
Object refToIntArrayA = new int[2];
Object refToIntArrayB = new int[2];

//Copy two values from the rawData


// array to each of the new two-
// element arrays.
System.arraycopy(
rawData,0,refToIntArrayA,0,2);
System.arraycopy(
rawData,2,refToIntArrayB,0,2);

//Create a two-element array of


// type Object[]. Populate each
// element with a reference to one
// of the two-element int arrays
// created and populated earlier.
Object[] refToObjArray =
{refToIntArrayA,refToIntArrayB};

//Invoke a method that will


// display the values stored in
// each of the two-element int
// arrays whose references are
// stored in the two-element array
// of type Object[].
new Samp120Class().
displayArrayData(refToObjArray);
}//end main
}//end class Samp120
//===================================//

class Samp120Class{
public static void displayYourName(){
System.out.println("Samp120");
System.out.println(
"Richard Baldwin");
}//end displayYourName()

public void displayArrayData(


Object[] refToObjArray){
for(int j = 0;
j<refToObjArray.length;j++){
//Note the following two rqmts to
// cast from type Object to
// type int[].
for(int i=0;
i<((int[])refToObjArray[j]).
length;i++){
System.out.print(
((int[])refToObjArray[j])[i]
+ " ");
}//end inner for loop
System.out.println();
}//end outer for loop
}//end displayArrayData()
}//end class Samp120Class

-end-

Copyright 2001, Richard G. Baldwin. Reproduction in whole or in part in any form or


medium without express written permission from Richard Baldwin is prohibited.

About the author


Richard Baldwin is a college professor (at Austin Community College in Austin, TX)
and private consultant whose primary focus is a combination of Java and XML. In
addition to the many platform-independent benefits of Java applications, he believes that
a combination of Java and XML will become the primary driving force in the delivery of
structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a


combination of the two. He frequently provides onsite Java and/or XML training at the
high-tech companies located in and around Austin, Texas. He is the author of Baldwin's
Java Programming Tutorials, which has gained a worldwide following among
experienced and aspiring Java programmers. He has also published articles on Java
Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years
of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-

Introduction to Object-Oriented Programming, Sample


Programs, Set 3
Published: December 1, 2001
By Richard G. Baldwin

Java Programming Tutorial # 9002

• Preface
• Sample Programs
• About the Author

Preface
This is the third and last in a miniseries of lessons designed specifically to help the
students in my "Introduction to Object-Oriented Programming" course study for their
exams. However, others may find the lesson useful as well.

The lesson consists of a set of simple programs, each designed to illustrate one or more
important Java OOP concepts. The concepts involved are identified in the comments at
the beginning of each program.
The programs are designed to illustrate the code without providing a detailed discussion
of the code. You are referred to the other lessons in my online Java tutorials for detailed
discussions of the OOP concepts illustrated by these programs.

Sample Programs
Program Samp122.java

/*File Samp122
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the Date class to get and
to manipulate the current time.

The output consists of the following


six lines of text. The program
displays the current time in the format
shown when the program is run.

Samp122
The current time is:
8:49:57 PM CST
One hour will be:
9:49:57 PM CST
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp122{
public static void main(
String[] args){
Samp122Class.doDate();
}//end main
}//end class Samp122
//===================================//

class Samp122Class{
public static void doDate(){
System.out.println("Samp122");
Date now = new Date();
long millisNow = now.getTime();
long oneHourMillis =
millisNow + 60*60*1000;
Date oneHour = new Date(
oneHourMillis);
System.out.println(
"The current time is:\n"
+ DateFormat.getTimeInstance(
DateFormat.FULL).
format(now));
System.out.println(
"One hour will be:\n"
+ DateFormat.
getTimeInstance(
DateFormat.FULL).
format(oneHour));

System.out.println(
"Richard Baldwin");
}//end doDate()
}//end class

Program Samp124.java

/*File Samp124
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the Date class to get and
to manipulate the current time.

The output consists of the following


six lines of text. The program
displays the current time in the format
shown when the program is run.

Samp124
The current time is:
8:39 PM
One-half hour from now will be:
9:09 PM
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp124{
public static void main(
String[] args){
Samp124Class.doDate();
}//end main
}//end class Samp124
//===================================//

class Samp124Class{
public static void doDate(){
System.out.println("Samp124");
Date now = new Date();
long millisNow = now.getTime();
long oneHalfHourMillis =
millisNow + 60*30*1000;
Date oneHalfHour = new Date(
oneHalfHourMillis);
System.out.println(
"The current time is:\n"
+ DateFormat.
getTimeInstance(
DateFormat.SHORT).
format(now));
System.out.println(
"One-half hour will be:\n"
+ DateFormat.
getTimeInstance(
DateFormat.SHORT).
format(oneHalfHour));

System.out.println(
"Richard Baldwin");
}//end doDate()
}//end class

Program Samp126.java

/*File Samp126
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the Date class to get and
to manipulate the current date.

The output consists of the following


six lines of text. The program
displays the current date in the format
shown when the program is run.

Samp126
The current date is:
12/1/01
Tomorrow will be:
12/2/01
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp126{
public static void main(
String[] args){
Samp126Class.doDate();
}//end main
}//end class Samp126
//===================================//

class Samp126Class{
public static void doDate(){
System.out.println("Samp126");
Date now = new Date();
long millisNow = now.getTime();
long oneDayMillis =
millisNow + 60*60*1000*24;
Date oneDay = new Date(
oneDayMillis);
System.out.println(
"The current date is:\n"
+ DateFormat.
getDateInstance(
DateFormat.SHORT).
format(now));
System.out.println(
"Tomorrow will be:\n"
+ DateFormat.
getDateInstance(
DateFormat.SHORT).
format(oneDay));

System.out.println(
"Richard Baldwin");
}//end doDate()
}//end class

Program Samp128.java

/*File Samp128
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the Date class to get and
to manipulate the current date.

The output consists of the following


six lines of text. The program
displays the current date in the format
shown when the program is run.

Samp128
The current date is:
Dec 1, 2001
Tomorrow will be:
Dec 2, 2001
Richard Baldwin

**************************************/

import java.util.*;
import java.text.*;
public class Samp128{
public static void main(
String[] args){
Samp128Class.doDate();
}//end main
}//end class Samp128
//===================================//

class Samp128Class{
public static void doDate(){
System.out.println("Samp128");
Date now = new Date();
long millisNow = now.getTime();
long oneDayMillis =
millisNow + 60*60*1000*24;
Date oneDay = new Date(
oneDayMillis);
System.out.println(
"The current date is:\n"
+ DateFormat.getDateInstance().
format(now));
System.out.println(
"Tomorrow will be:\n"
+ DateFormat.getDateInstance().
format(oneDay));

System.out.println(
"Richard Baldwin");
}//end doDate()
}//end class

Program Samp130.java

/*File Samp130
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
The use of the Date class to get and
to manipulate the current date and
time.

The output consists of the following


six lines of text. The program
displays the current date and time
in the format shown when the program is
run.

Samp130
The current date and time is:
Sat Dec 01 19:59:25 CST 2001
One hour from now will be:
Sat Dec 01 20:59:25 CST 2001
Richard Baldwin

**************************************/

import java.util.*;
public class Samp130{
public static void main(
String[] args){
Samp130Class.doDate();
}//end main
}//end class Samp130
//===================================//

class Samp130Class{
public static void doDate(){
System.out.println("Samp130");
Date now = new Date();
long millisNow = now.getTime();
long oneHourMillis =
millisNow + 60*60*1000;
Date oneHour = new Date(
oneHourMillis);
System.out.println(
"The current date and time is:\n"
+ now);
System.out.println(
"One hour from now will be:\n"
+ oneHour);
System.out.println(
"Richard Baldwin");
}//end doDate()
}//end class

Program Samp138.java

/*File Samp138
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
A method that returns a reference to an
object.
The output consists of the following
five lines of text.

Samp138
5
Incoming null ref
5
Terminating, Richard Baldwin

**************************************/

class Samp138 {
int instanceVar = 5;

public static void main(


String[] args){
Samp138 firstRefToObj =
new Samp138();
System.out.println("Samp138");
showInstanceVar(firstRefToObj);

Samp138 secondRefToObj =
Samp138Class.returnRefToObj(
firstRefToObj);

firstRefToObj = null;

showInstanceVar(firstRefToObj);
showInstanceVar(secondRefToObj);

System.out.println("Terminating,"
+ new Samp138Name());
}//end main
//---------------------------------//

static void showInstanceVar(


Samp138 refToObj){
try{
System.out.println(
refToObj.instanceVar);
}catch(NullPointerException e){
System.out.println(
"Incoming null ref");
}//end catch
}//end showInstanceVar
}//End Samp138
//===================================//

class Samp138Class{

static Samp138 returnRefToObj(


Samp138 refToObj){
//Return the incoming reference
return refToObj;
}//end returnRefToObj()
}//end class Samp138Class
//===================================//

class Samp138Name{
public String toString(){
return " Richard Baldwin";
}//end toString()
}//end Samp138Name

Program Samp140.java

/*File Samp140
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
A method that returns a reference to an
object. Also illustrates the ability
to deal with references to objects
in a fairly complicated manner. This
is simply an exercise in handling
refs to objects.

The program first prompts the user to


enter a single character at the
keyboard.

The program then displays a value on


the screen as shown below.

Finally, the program displays a


termination message which includes your
name.

The program must produce the correct


output for any single keyboard
character. The following sample
outputs can be used to determine the
methodology required to produce the
correct results.

For an input character of A,


the output must be:

Samp140
Enter a keyboard char -> A
70
Terminating, Richard Baldwin

For an input character of a,


the output must be:
Samp140
Enter a keyboard char -> a
102
Terminating, Richard Baldwin

For an input character of 0,


the output must be:

Samp140
Enter a keyboard char -> 0
53
Terminating, Richard Baldwin

**************************************/

class Samp140 {
int instanceVar;

public static void main(


String[] args)
throws java.io.IOException{
Samp140 refToObj =
new Samp140HelperA().
returnRefToObj();
System.out.println("Samp140");
System.out.print(
"Enter a keyboard char -> ");
int charIn = System.in.read();
refToObj.instanceVar = charIn;
refToObj = new Samp140Helper(
refToObj).returnRefToObj();
show(refToObj);
System.out.println("Terminating,"
+ new Samp140Name());
}//end main

static void show(Samp140 refToObj){


System.out.println(
refToObj.instanceVar);
}//end show
}//End Samp140 class
//===================================//

class Samp140Helper{
int instanceVar;

Samp140Helper(Samp140 obj){
instanceVar = obj.instanceVar;
}//end constructor

Samp140 returnRefToObj(){
Samp140 newObj = new Samp140();
newObj.instanceVar =
this.instanceVar + 5;
return newObj;
}//end returnRefToObj()

}//end Samp140Helper

class Samp140HelperA{
Samp140 returnRefToObj(){
return new Samp140();
}//end returnRefToObj()
}//end Samp140HelperA

class Samp140Name{
public String toString(){
return " Richard Baldwin";
}//end toString()
}//end Samp140Name

Program Samp150.java

/*File Samp150
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the getClass method of the
Object class, and a couple of methods
of the Class class.

Note that the method named getClassObj


in the class named Samp150Class must
not be overloaded.

Depending on whether the value of rNum


is odd or even, the output consists of
one of the following groups of four
lines of text. Because the program
generates the data on the basis of a
random value, the output will differ
from one run to the next. However, in
all cases, the output will match one
of the groups of four lines of text
shown below.

Samp150 String
Richard Baldwin
java.lang.String
class java.lang.Object

Samp150 Button
Richard Baldwin
java.awt.Button
class java.awt.Component

**************************************/

import java.awt.*;
import java.util.*;

class Samp150{

public static void main(


String[] args){
Random rGen = new Random(
new Date().getTime());
int rNum = rGen.nextInt()%2;

Class refToClassObj;
if( rNum == 0){
System.out.println(
"Samp150 String");
refToClassObj = Samp150Class.
getClassObj(new String(""));
}else{
System.out.println(
"Samp150 Button");
refToClassObj = Samp150Class.
getClassObj(new Button());
}//end else

System.out.println(refToClassObj.
getName());
System.out.println(refToClassObj.
getSuperclass());
}//end main
}//end class Samp150
//===================================//

class Samp150Class{
public static Class getClassObj(
Object objectIn){
System.out.println(
"Richard Baldwin");
Class refToClassObj = null;
try{
refToClassObj = objectIn.
getClass();
}catch(Exception e){
System.out.println(e);}
return refToClassObj;
}//end getClassObj();
}//end class Samp150Class

Program Samp160.java
/*File Samp160
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the forName() method of the
class named Class.

Depending on whether the value of rNum


is odd or even, the output consists of
one of the following groups of four
lines of text. Because the program
generates the data on the basis of a
random value, the output will differ
from one run to the next. However, in
all cases, the output will match one of
the groups of four lines of text shown
below.

Samp160 Button
Richard Baldwin
java.awt.Button
class java.awt.Component

Samp160 String
Richard Baldwin
java.lang.String
class java.lang.Object

**************************************/

import java.awt.*;
import java.util.*;

class Samp160{

public static void main(


String[] args){
Random rGen = new Random(
new Date().getTime());
int rNum = rGen.nextInt()%2;

Class refToClassObj;
if(rNum == 0){
System.out.println(
"Samp160 String");
refToClassObj = Samp160Class.
returnClassObj(
"java.lang.String");
}else{
System.out.println(
"Samp160 Button");
refToClassObj = Samp160Class.
returnClassObj(
"java.awt.Button");
}//end else

System.out.println(refToClassObj.
getName());
System.out.println(refToClassObj.
getSuperclass());
}//end main
}//end class Samp160
//===================================//

class Samp160Class{
public static Class returnClassObj(
String stringIn){
System.out.println(
"Richard Baldwin");
Class refToClassObj = null;
try{
refToClassObj = Class.forName(
stringIn);
}catch(Exception e){
System.out.println(e);}
return refToClassObj;
}//end returnClassObj();
}//end class Samp160Class

Program Samp170.java

/*File Samp170
Copyright 2001, R.G.Baldwin
Rev 11/30/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the asList method of the Arrays
class to get a List view of an array.
Note that changes to the List view
write through to the underlying array.

The output consists of the following


four lines of text.

Samp170
Richard Baldwin
A B C
Ax Bx Cx

**************************************/

import java.util.*;
class Samp170{
public static void main(
String[] args){
System.out.println(
Samp170Class.showYourName());

Object[] refToArray =
{"A","B","C"};
//Display array contents
for(int cnt=0;
cnt<refToArray.length;cnt++){
System.out.print(
refToArray[cnt] + " ");
}//end for loop
System.out.println();

List refToList = Samp170Class.


returnListView(refToArray);
ListIterator iterator =
refToList.listIterator();
//Modify List contents
while(iterator.hasNext()){
Object var3 = iterator.next();
iterator.set(var3 + "x");
}//end while

//Display modified array contents


for(int cnt=0;
cnt<refToArray.length;cnt++){
System.out.print(
refToArray[cnt] + " ");
}//end for loop
System.out.println();
}//end main
}//end class Samp170
//===================================//

class Samp170Class{
static String showYourName(){
System.out.println("Samp170");
return "Richard Baldwin";
}//end showYourName()

static List returnListView(


Object[] refToArray){
return Arrays.asList(refToArray);
}//end returnListView

}//end class Samp170Class

-end-

Copyright 2001, Richard G. Baldwin. Reproduction in whole or in part in any form or


medium without express written permission from Richard Baldwin is prohibited.
About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX)
and private consultant whose primary focus is a combination of Java and XML. In
addition to the many platform-independent benefits of Java applications, he believes that
a combination of Java and XML will become the primary driving force in the delivery of
structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a


combination of the two. He frequently provides onsite Java and/or XML training at the
high-tech companies located in and around Austin, Texas. He is the author of Baldwin's
Java Programming Tutorials, which has gained a worldwide following among
experienced and aspiring Java programmers. He has also published articles on Java
Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years
of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-

Você também pode gostar