Java Reference
In-Depth Information
this.surname = surname;
}
@Override
public String toString() {
return firstName + " " + surname;
}
private String firstName; // First name of person
private String surname; // Second name of person
}
The only data members are the
String
members to store the first and second names for a person. You
override the inherited version of the
toString()
method to get better output when
Person
class objects are
used as arguments to the
println()
method. Now you can define an example with which you can try your
skills as a casting director.
TRY IT OUT: Creating the Crowd
You can now add a class containing a
main()
method to try storing
Person
objects in a vector. You can
call it
TryVector
:
import java.util.Vector;
import java.util.ListIterator;
import java.io.*;
public class TryVector {
public static void main(String[] args) {
Person aPerson = null; // A person object
Vector<Person> filmCast = new Vector<>();
// Populate the film cast
while(true) {
// Indefinite loop
aPerson = readPerson();
// Read in a film star
if(aPerson == null) {
// If null obtained...
break;
// We are done...
}
filmCast.add(aPerson);
// Otherwise, add to the cast
}
int count = filmCast.size();
System.out.println("You added " + count +
(count == 1 ? " person": " people") + " to the
cast:");
// Show who is in the cast using an iterator
ListIterator<Person> thisLot = filmCast.listIterator();