System.out.println()

advertisement
// Java2101.java
This program tests the features of the <Bank> class.
public class Java2101
{
public static void main (String args[])
{
System.out.println("\nJAVA2101.JAVA\n");
Bank tom = new Bank(5000.0,10000.0);
Bank sue = new Bank(3000.0,15000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom's savings balance: " + tom.getSavingsBalance());
System.out.println("Sue's checking balance: " + sue.getCheckingBalance());
System.out.println("Sue's savings balance: " + sue.getSavingsBalance());
System.out.println();
System.out.println("Tom makes a $1000.00 checking withdrawal");
tom.makeCheckingWithdrawal(1000.0);
System.out.println("Tom makes a $2000.00 savings withdrawal");
tom.makeSavingsWithdrawal(2000.0);
System.out.println("Sue makes a $1500.00 checking deposit");
sue.makeCheckingDeposit(1500.0);
System.out.println("Sue makes a $3000.00 savings deposit");
sue.makeSavingsDeposit(3000.0);
System.out.println();
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom's savings balance: " + tom.getSavingsBalance());
System.out.println("Sue's checking balance: " + sue.getCheckingBalance());
System.out.println("Sue's savings balance: " + sue.getSavingsBalance());
System.out.println();
}
}
class Bank
{
private double checking;
private double savings;
public Bank()
{
checking = 0.0;
savings = 0.0;
}
public Bank(double c, double s)
{
checking = c;
savings = s;
}
public double getCheckingBalance()
public double getSavingsBalance()
public void makeCheckingDeposit(double amount)
public void makeSavingsDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
public void makeSavingsWithdrawal(double amount)
public void closeCheckingAccount()
public void closeSavingsAccount()
}
{
{
{
{
{
{
{
{
return checking;
return savings;
checking += amount;
savings += amount;
checking -= amount;
savings -= amount;
checking = 0;
savings = 0;
}
}
}
}
}
}
}
}
// Java2102.java
// This program uses a simplified <Bank> class, which will be used for future
// program examples in this chapter.
public class Java2102
{
public static void main (String args[])
{
System.out.println("\nJAVA2102.JAVA\n");
Bank tom = new Bank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
class Bank
{
private double checking;
public Bank(double c)
{ checking = c; }
public double getCheckingBalance()
{ return checking; }
public void makeCheckingDeposit(double amount)
{ checking += amount; }
public void makeCheckingWithdrawal(double amount) { checking -= amount; }
}
// Java2103.java
// The former <Bank> class is now a <Bank> interface.
// Only the method headings are shown. The program does not compile.
public class Java2103
{
public static void main (String args[])
{
System.out.println("\nJAVA2103.JAVA\n");
Bank tom = new Bank();
System.out.println();
}
}
interface Bank
{
public double getCheckingBalance();
public void makeCheckingDeposit(double amount);
public void makeCheckingWithdrawal(double amount);
}
Program Differences
Typical Program
Java2103.java
Uses class
Uses interface
Has methods with program
statements
No statements, only method
headings
Methods headings have no
semi-colons
Method headings have semicolons
Class has a constructor
There is no constructor
There are fields to store data
There are no fields
Java Interfaces
A Java Interface provides a group of
method signatures that will be available
for any client of a class that implements
the interface.
Implementation details of the interface
methods are neither required nor
desired at the interface level.
Java Collection Hierarchy
Collection
Interface
List
Interface
ArrayList
class
LinkedList
class
Set
Interface
HashSet
class
TreeSet
class
Collections
A collection is a group of objects.
Linear Collections
A linear collection stores its elements in
a specific order.
Linear collections can have duplicate
elements.
Lists
A list is a linear collection that allows
access to any element in the list.
Examples of list data structures are
Java static arrays, ArrayLists,
Strings and Files.
Unordered Collections
An unordered collection stores elements
without order.
Bags
A bag is an unordered collection
that can have duplicate elements.
Sets
A set is an unordered collection
without any duplicate elements.
// Java2104.java
// The <MyBank> class implements the <Bank> interface. The program now compiles and executes.
public class Java2104
{
public static void main (String args[])
{
System.out.println("\nJAVA2104.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
interface Bank
{
public double getCheckingBalance();
public void makeCheckingDeposit(double amount);
public void makeCheckingWithdrawal(double amount);
}
class MyBank implements Bank
{
private double checking;
public MyBank(double c)
public double getCheckingBalance()
public void makeCheckingDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
}
{ checking = c;
{ return checking;
{ checking += amount;
{ checking -= amount;
}
}
}
}
// Java2105.java
// An interface is "abstract" and its methods are also "abstract". The <abstract> keyword is optional.
public class Java2105
{
public static void main (String args[])
{
System.out.println("\nJAVA2105.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract interface Bank
{
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
class MyBank implements Bank
{
private double checking;
public MyBank(double c)
public double getCheckingBalance()
public void makeCheckingDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
}
{ checking = c;
{ return checking;
{ checking += amount;
{ checking -= amount;
}
}
}
}
Implementation Rule
A class, which implements an
interface, must implement every
method declared in the interface.
// Java2106.java
// This program partially implements the <Bank> class.
Now the program does not compile.
public class Java2106
{
public static void main (String args[])
{
System.out.println("\nJAVA2106.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract interface Bank
{
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
class MyBank implements Bank
{
private double checking;
public MyBank(double c)
public void makeCheckingDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
}
{ checking = c; }
{ checking += amount; }
{ checking -= amount; }
// Java2107.java
This program demonstrates that it is possible to implement an interface
//
and define additional methods that are not declared in the interface.
public class Java2107
{
public static void main (String args[])
{
System.out.println("\nJAVA2107.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
tom.closeAccount();
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract interface Bank
{
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
class MyBank implements Bank
{
private double checking;
public MyBank(double c)
{ checking = c;
}
public double getCheckingBalance()
{ return checking;
}
public void makeCheckingDeposit(double amount)
{ checking += amount; }
public void makeCheckingWithdrawal(double amount) { checking -= amount; }
public void closeAccount()
{ checking = 0;
}
}
// Java2108.java
// This program shows how one class, <BankAccounts> can implement two
// interfaces <Checking> and <Savings>.
public class Java2108
{
public static void main (String args[])
{
System.out.println("\nJAVA2108.JAVA\n");
BankAccounts tom = new BankAccounts(5000.0,7500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
System.out.println("Tom's savings balance: " + tom.getSavingsBalance());
System.out.println("Tom makes a $1500.00 savings deposit");
tom.makeSavingsDeposit(1500.0);
System.out.println("Tom's savings balance: " + tom.getSavingsBalance());
System.out.println("Tom makes a $2500.00 savings withdrawal");
tom.makeSavingsWithdrawal(2500.0);
System.out.println("Tom's savings balance: " + tom.getSavingsBalance());
System.out.println();
}
}
abstract interface Checking
{
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
abstract interface Savings
{
public abstract double getSavingsBalance();
public abstract void makeSavingsDeposit(double amount);
public abstract void makeSavingsWithdrawal(double amount);
}
class BankAccounts implements Checking,Savings
{
}
private double checking;
private double savings;
public BankAccounts(double c, double s)
{ checking = c; savings = s; }
public double getCheckingBalance()
public double getSavingsBalance()
public void makeCheckingDeposit(double amount)
public void makeSavingsDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
public void makeSavingsWithdrawal(double amount)
{ return checking;
{ return savings;
{ checking += amount;
{ savings += amount;
{ checking -= amount;
{ savings -= amount;
}
}
}
}
}
}
// Java2109.java
// This program shows that it is possible to have a field in an interface, but it
// must be final and initialized.
public class Java2109
{
public static void main (String args[])
{
System.out.println("\nJAVA2109.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Computing interest");
tom.computeInterest();
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract interface Bank
{
public final double rate = 0.05;
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
public abstract void computeInterest();
}
class MyBank implements Bank
{
private double checking;
private double interest;
public MyBank(double c)
{
checking = c;
interest = 0.0;
}
public double getCheckingBalance()
public void makeCheckingDeposit(double amount)
public void makeCheckingWithdrawal(double amount)
public void computeInterest()
{
interest = checking * rate;
checking += interest;
}
}
{ return checking;
}
{ checking += amount; }
{ checking -= amount; }
Using Fields in an Interface
Fields may be used in an interface declaration.
All fields must have an initialized value.
Field values are constant and cannot be changed.
The final keyword is optional. Final is implied.
// Java2110.java
// This program uses an abstract <Bank> class, rather than a <Bank> interface.
// There appears no difference between an abstract class and an interface.
public class Java2110
{
public static void main (String args[])
{
System.out.println("\nJAVA2110.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract class Bank
{
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
class MyBank extends Bank
{
private double checking;
public MyBank(double c)
{ checking = c;
}
public double getCheckingBalance()
{ return checking;
}
public void makeCheckingDeposit(double amount)
{ checking += amount; }
public void makeCheckingWithdrawal(double amount) { checking -= amount; }
}
// Java2111.java
// An abstract class can have both abstract members and concrete members.
// An interface can only have abstract members.
public class Java2111
{
public static void main (String args[])
{
System.out.println("\nJAVA2111.JAVA\n");
MyBank tom = new MyBank(5000.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $1500.00 checking deposit");
tom.makeCheckingDeposit(1500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println("Tom makes a $2500.00 checking withdrawal");
tom.makeCheckingWithdrawal(2500.0);
System.out.println("Tom's checking balance: " + tom.getCheckingBalance());
System.out.println();
}
}
abstract class Bank
{
protected double checking;
protected Bank(double c)
{ checking = c;
}
public abstract double getCheckingBalance();
public abstract void makeCheckingDeposit(double amount);
public abstract void makeCheckingWithdrawal(double amount);
}
class MyBank extends Bank
{
protected MyBank(double c)
{ super(c);
}
public double getCheckingBalance()
{ return checking;
}
public void makeCheckingDeposit(double amount)
{ checking += amount; }
public void makeCheckingWithdrawal(double amount) { checking -= amount; }
}
Abstract Interfaces &
Abstract Classes
All methods of an interface
must be abstract.
Methods in an abstract class
may be abstract or concrete.
Interfaces vs. Abstract Classes
Interface
Abstract Class
Abstract methods only Abstract and concrete
methods
No constructor allowed Can have a constructor
Needs a class to
Needs a subclass to
implement the interface implement the abstract
methods
Only final data fields
Any data field is
are allowed
allowed
Cannot instantiate an
Cannot instantiate an
object
object
Inheritance vs. Implementation
Inheritance of Classes
A class is a blueprint for creating an object.
An inherited class (subclass) is a modified
blueprint for creating an specialized object.
Inheritance vs. Implementation
Implementation of Interfaces
A interface is something abstract. It is like a general
idea you have before anyone can create the blueprints.
Polymorphism
Polymorphism
allows a single
accessing feature,
such as an operator,
method or class
identifier, to have
many forms.
// Java2112.java
// This program displays the information of three different classes with 3 different <getData> methods.
public class Java2112
{
public static void main (String args[])
{
Mammal animal1 = new Mammal();
Bird animal2 = new Bird();
Fish animal3 = new Fish();
getData1(animal1);
getData2(animal2);
getData3(animal3);
System.out.println();
}
public static void getData1(Mammal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
public static void getData2(Bird obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
public static void getData3(Fish obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
}
abstract interface Animal
{
abstract String getType();
abstract String getMove();
}
class Mammal implements Animal
{
String animalType;
public Mammal()
{ animalType = "Mammal"; }
public String getType()
{ return animalType;
}
public String getMove()
{ return " walks.";
}
}
class Bird implements Animal
{
String animalType;
public Bird()
{ animalType = "Bird";
public String getType()
{ return animalType;
public String getMove()
{ return " flies.";
}
class Fish implements Animal
{
String animalType;
public Fish()
{ animalType = "Fish";
public String getType()
{ return animalType;
public String getMove()
{ return " swims.";
}
}
}
}
}
}
}
// Java2113.java
// This program is almost identical to Java2112.java.
// All three of the <getData> use (Animal obj) in the method heading.
public class Java2113
{
public static void main (String args[])
{
System.out.println("\nJAVA2113.JAVA\n");
Mammal animal1 = new Mammal();
Bird animal2 = new Bird();
Fish animal3 = new Fish();
getData1(animal1);
getData2(animal2);
getData3(animal3);
System.out.println();
}
public static void getData1(Animal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
public static void getData2(Animal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
public static void getData3(Animal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
}
// Java2114.java
// This program demonstrates "polymorphism".
// The <getData> method displays the correct data polymorphically.
public class Java2114
{
public static void main (String args[])
{
System.out.println("\nJAVA2114.JAVA\n");
Mammal animal1 = new Mammal();
Bird animal2 = new Bird();
Fish animal3 = new Fish();
getData(animal1);
getData(animal2);
getData(animal3);
System.out.println();
}
public static void getData(Animal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
}
// Java2115.java
// This program demonstrates that polymorphism can be done
// with abstract classes in the same manner as abstract interfaces.
public class Java2115
{
public static void main (String args[])
{
System.out.println("\nJAVA2115.JAVA\n");
Mammal animal1 = new Mammal();
Bird animal2 = new Bird();
Fish animal3 = new Fish();
getData(animal1);
getData(animal2);
getData(animal3);
System.out.println();
}
public static void getData(Animal obj)
{
System.out.println("A " + obj.getType() + obj.getMove());
}
}
abstract class Animal
{
abstract String getType();
abstract String getMove();
}
class Mammal extends Animal
{
String animalType;
public Mammal()
{ animalType = "Mammal"; }
public String getType()
{ return animalType;
}
public String getMove()
{ return " walks.";
}
}
class Bird extends Animal
{
String animalType;
public Bird()
{ animalType = "Bird";
public String getType()
{ return animalType;
public String getMove()
{ return " flies.";
}
class Fish extends Animal
{
String animalType;
public Fish()
{ animalType = "Fish";
public String getType()
{ return animalType;
public String getMove()
{ return " swims.";
}
}
}
}
}
}
}
Polymorphism Steps
Use the following steps to use a method
polymorphically
Declare an interface or abstract superclass with
1
the necessary abstract methods.
2
3
Implement the abstract methods in multiple
classes using implementations appropriate to
each class.
Declare some method that performs a common
purpose for each of the methods, but the actual
execution depends on the implementation of
the specified class object.
The parameter heading of this method needs to
use the interface identifier or the super class
identifier.
And now, a quote from the
former chief reader of APCS…
Do not use Computer Science to teach
the case study, use the case study to
teach Computer Science.
--- Chris Nevison
Question:
How does
GridWorld
Work?
Every object in
GridWorld moves
differently.
What makes each
object move?
Answer:
Polymorphism
for (Actor a : actors)
{
// only act if another actor hasn't removed a
if (a.getGrid() == gr)
a.act();
}
Actor
superclass
public void act()
{
setDirection(getDirection() +
Location.HALF_CIRCLE);
}
Rock
subclass
of Actor
public void act()
{
}
Flower
subclass
of Actor
public void act()
{
Color c = getColor();
int red = (int) (c.getRed() * (1 - DARKENING_FACTOR));
int green = (int) (c.getGreen() * (1 - DARKENING_FACTOR));
int blue = (int) (c.getBlue() * (1 - DARKENING_FACTOR));
setColor(new Color(red, green, blue));
}
Bug
subclass
of Actor
public void act()
{
if (canMove())
move();
else
turn();
}
Critter
subclass
of Actor
public void act()
{
if (getGrid() == null) return;
ArrayList<Actor> actors = getActors();
processActors(actors);
ArrayList<Location> moveLocs = getMoveLocations();
Location loc = selectMoveLocation(moveLocs);
makeMove(loc);
}
BoxBug
subclass
of Bug
public void act()
{
if (steps < sideLength &&
canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
}
}
OctagonBug
subclass
of Bug
public void act()
{
if (steps < sideLength &&
canMove())
{
move();
steps++;
}
else
{
turn();
steps = 0;
}
}
// Java2116.java
// This is a not a runnable program.
// You see the <List> interface below, as it is described by the
// College Board AP Computer Science course description.
interface List<E>
{
public int size();
// returns the number of elements in list
public boolean add(E obj);
// appends obj to the end of list; returns true
public void add(int index, E obj);
// inserts obj at position index (0 <= index <= size),
// moving elements to the right (adds 1 to their indices) and adjusts size
public E get(int index);
// returns element at position index
public E set(int index, E obj);
// replaces the element at position index with obj
// returns the element formerly at the specified position
public E remove(int index);
// removes element from position index, moving elements
// at position index+1 and higher to the left
// (subtracts 1 from their indices) and adjusts size
// returns the element formerly at the specified position
}
// Java2117.java
// This program implement the <IntList> interface.
// The interface and the implementation is intentionally not generic.
// Every method and storage is designed to work with <int> values only.
public class Java2117
{
public static void main (String args[])
{
System.out.println("\nJAVA2117.JAVA\n");
MyIntList numbers = new MyIntList();
numbers.add(100);
numbers.add(200);
numbers.add(300);
System.out.println("numbers size is " + numbers.size());
System.out.println(numbers);
numbers.add(1,999);
System.out.println("numbers size is " + numbers.size());
System.out.println(numbers);
System.out.println("Element at index 2 is " + numbers.get(2));
numbers.set(2,555);
System.out.println("numbers size is " + numbers.size());
System.out.println(numbers);
numbers.remove(1);
System.out.println("numbers size is " + numbers.size());
System.out.println(numbers);
}
}
interface IntList
{
public int size();
public boolean add(int num);
public void add(int index, int num);
public int get(int index);
public int set(int index, int num);
public int remove(int index);
}
class MyIntList implements IntList
{
private int intArray[];
private int size;
public MyIntList()
{
intArray = new int[10000];
size = 0;
}
public int size() { return size; }
public boolean add(int num)
{
intArray[size] = num;
size++;
return true;
}
public void add(int index, int num)
{
for (int k = size; k >= index; k--)
intArray[k] = intArray[k-1];
intArray[index] = num;
size++;
}
The reason the add method
needs to return a boolean
value is because it
implements the Collection
interface which is also used
for Sets.
Returning true means a
successful add.
In the case of a Set,
duplicate elements are not
allowed.
Trying to add a duplicate
would cause false to be
returned indicating it was
not a successful add.
public int get(int index) { return intArray[index]; }
public int set(int index, int num)
{
int temp = intArray[index];
intArray[index] = num;
return temp;
}
public int remove(int index)
{
int temp = intArray[index];
for (int k = index; k < size-1; k++)
intArray[k] = intArray[k+1];
size--;
return temp;
}
public String toString()
{
String temp = "";
for (int k = 0; k < size; k++)
temp = temp + intArray[k] + " ";
return temp;
}
}
// Java2118.java
// This program implement the <List> interface.
// The interface and the implementation is now generic.
// In this program every instance of E will be replaced by String.
public class Java2118
{
public static void main (String args[])
{
System.out.println("\nJAVA2118.JAVA\n");
MyList<String> names = new MyList<String>();
names.add("Isolde");
names.add("John");
names.add("Greg");
System.out.println("names size is " + names.size());
System.out.println(names);
names.add(1,"Maria");
System.out.println("names size is " + names.size());
System.out.println(names);
System.out.println("Element at index 2 is " + names.get(2));
names.set(2,"Heidi");
System.out.println("names size is " + names.size());
System.out.println(names);
names.remove(1);
System.out.println("names size is " + names.size());
System.out.println(names);
}
}
MyList<String> names = new MyList<String>();
interface List<E>
{
public int size();
public boolean add(E obj);
Working with
Generics is like
having the ability to
pass a parameter –
which is a datatype
– to a class.
public void add(int index, E obj);
public E get(int index);
public E set(int index, E obj);
public E remove(int index);
}
MyList<String> names = new MyList<String>();
interface List<String>
{
public int size();
public boolean add(String obj);
It is as if all of the
Es magically
change to String
which is the
datatype you want
to work with.
public void add(int index, String obj);
public String get(int index);
public String set(int index, String obj);
public String remove(int index);
}
class MyList<E> implements List<E>
{
private Object array[];
private int size;
public MyList()
{
array = new Object[10000];
size = 0;
}
public int size() { return size; }
public boolean add(E obj)
{
array[size] = obj;
size++;
return true;
}
public void add(int index, E obj)
{
for (int k = size; k >= index; k--)
array[k] = array[k-1];
array[index] = obj;
size++;
}
Note that the size
method returns an int.
It does not return the
Generic E object.
This is because the size
of the list is always an
int, regardless of what
is stored in the array.
public E get(int index) { return (E) array[index]; }
public E set(int index, E obj)
{
E temp = (E) array[index];
array[index] = obj;
return temp;
}
public E remove(int index)
{
E temp = (E) array[index];
for (int k = index; k < size-1; k++)
array[k] = array[k+1];
size--;
return temp;
}
public String toString()
{
String temp = "";
for (int k = 0; k < size; k++)
temp = temp + array[k] + " ";
return temp;
}
}
Typecasting
with Generics
Download