A review example. Are any of the statements illegal, and if not,
what's the output?
import java.util.*;
public class ReviewOne {
public static void main(String [] args) {
Vector v = new Vector();
v.add(new A("Apples"));
v.add(new B("Bananas",3));
v.add("Oranges");
for (int i = 0; i< v.size(); ++i) {
System.out.println(v.elementAt(i));
}
A a = (A) v.elementAt(0); // wouldn't work without typecasting
a.m(" are green");
System.out.println(a);
a = (A) v.elementAt(1);
a.m(" are yellow");
//a.m(2);
System.out.println(a); // toString of B is called
B b = (B) v.elementAt(1);
b.m(1);
b.m(" and tasty");
System.out.println(b);
b = new B("Cucumbers",5);
String s = "Bagels";
v.setElementAt(new B(s,1), 2);
s = "Pretzels";
for (int i = 0; i< v.size(); ++i) {
System.out.println(v.elementAt(i));
}
}
}
class A {
protected String stuff;
public A(String stuff) {
this.stuff = stuff;
}
public void m(String s) {
stuff = stuff + s;
}
public String toString() {
return "A: stuff = " + stuff;
}
}
class B extends A {
private int morestuff;
public B(String stuff, int morestuff) {
super(stuff);
this.morestuff = morestuff;
}
public void m(int n) {
morestuff = morestuff + n;
}
public String toString() {
return "B: stuff = " + stuff + " morestuff = " + morestuff;
}
}
This is an example from CSci 1211 course.