i am writing a program in bluej which consists of several classes that get user input and save them as String data. These Classes override each others methods and are meant to be displayed in a final class called CollegeList. However, for the class CollegeList i am not allowed in my assignment to extend these subclasses. Instead i am meant to use a bluej ‘uses relation’ and output these classes input and output in a for each loop. How can this be done? here is some of my code:
// College List
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class CollegeList
{
//Input Reader
Scanner scanner = new Scanner(System.in);
private ArrayList<Person> people;
//Main Public Method
public CollegeList()
{
people=new ArrayList<Person>();
}
public void main()//not allowed to extend
{
dataEntry();
}
public void getPeople(Person persons)
{
people.add(persons);
System.out.println(people);;
}
//*** Attempting to output preceding class Person in loop - Must be done this way
public void dataEntry()
{
for(Person persons: people)
{
persons.dataEntry();
}
}
}
The Person class:
import java.util.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;
public class Person extends Student
{
// instance variables for data types
public ArrayList<String> firstName;
public ArrayList<String> lastName;
public ArrayList<String> streetAdress;
public ArrayList<String> postCode;
public ArrayList<String> phoneNumber;
Scanner scanner = new Scanner(System.in);
/**
* Constructor for objects personal details.
*/
public Person()
{
firstName = new ArrayList<String>();
lastName = new ArrayList <String>();
streetAdress = new ArrayList<String>();
postCode = new ArrayList<String>();
phoneNumber = new ArrayList<String>();
}
/**
* Allows User to Enter Details into class Person and Displays it.
*/
public void dataEntry ()
{
System.out.print("Enter First Name: ");
firstName.add(scanner.nextLine());
System.out.print("Enter Last Name: ");
lastName.add(scanner.nextLine());
System.out.print("Enter Street Adress: ");
streetAdress.add(scanner.nextLine());
System.out.print("Enter Post Code: ");
postCode.add(scanner.nextLine());
System.out.print("Enter Phone Number: ");
phoneNumber.add(scanner.nextLine());
//display persons information on single line
System.out.println("The details are - " +
"Name: " +
firstName + "," +
"Surname: " +
lastName + "," +
"Street Adress: " +
streetAdress + "," +
"Post Code: " +
postCode + "," +
"Phone Number: " +
phoneNumber + "." );
}
}
From what I understood from your question is that you are asked to Use composition instead of inheritance.
Additionally there are some basic things that you should correct:
Personclass should not haveListoffirstName, lastNameetc. It should rather have them as simpleStringand then you can create aListofPersonas needed. You can then use for loop to iterate over this list as you want.Personshould not extendStudent, as logically every person is not a student.