CIS 260 – Multiclass Application - Implementing a 1:Many Relationship
Driver Class
package cis260.matos;
public class Driver {
/**
* demo: Person-to-Boat(s) relationship
*/
public static void main(String[] args) {
Person p1 = new Person("Maria", "123 Salsa Rd");
Person p2 = new Person("Charles Brown", "111 Peanuts Dr");
Boat b1 = new Boat("OH123", "Triton", 20);
Boat b2 = new Boat("OH555", "Neptune", 80);
Boat b3 = new Boat("OH777", "Honda", 10);
p1.addBoat(b1);
p1.show();
p2.addBoat(b2);
p2.addBoat(b3);
p2.show();
}
}
Person Class
package cis260.matos;
import java.util.ArrayList;
public class Person {
private String mName;
private String mAddress;
private ArrayList<Boat> mBoatList;
//constructor
public Person(String mName, String mAddress) {
super();
this.mName = mName;
this.mAddress = mAddress;
this.mBoatList = new ArrayList<Boat>();
}
//mutators
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmAddress() {
return mAddress;
}
public void setmAddress(String mAddress) {
this.mAddress = mAddress;
}
//user-defined methods
public void addBoat(Boat b)
{
this.mBoatList.add(b);
b.setmOwner(this);
}
public void show()
{
System.out.println("\nName: " + mName
+" Address: " + mAddress);
Boat b;
for(int i=0; imBoatList.size(); i++)
{
b = (Boat) mBoatList.get(i);
b.show();
}
}
}
Boat Class
package cis260.matos;
public class Boat {
private String mId;
private String mMaker;
private int mLength;
private Person mOwner;
public Boat(String mId, String mMaker, int mLength) {
super();
this.mId = mId;
this.mMaker = mMaker;
this.mLength = mLength;
}
public String getmId() {
return mId;
}
public void setmId(String mId) {
this.mId = mId;
}
public String getmMaker() {
return mMaker;
}
public void setmMaker(String mMaker) {
this.mMaker = mMaker;
}
public int getmLength() {
return mLength;
}
public void setmLength(int mLength) {
this.mLength = mLength;
}
public Person getmOwner() {
return mOwner;
}
public void setmOwner(Person mOwner) {
this.mOwner = mOwner;
}
//user-defined method
public void show()
{
String ownerName = "";
if (mOwner != null)
ownerName = this.getmOwner().getmName();
else
ownerName = "n.a";
System.out.println(" ID: " + mId
+ " Maker: " + mMaker
+ " length: " + mLength
+ " Owner: " + ownerName);
}
}
Console
Name: Maria Address: 123 Salsa Rd
ID: OH123 Maker: Triton length: 20 Owner: Maria
Name: Charles Brown Address: 111 Peanuts Dr
ID: OH555 Maker: Neptune length: 80 Owner: Charles Brown
ID: OH777 Maker: Honda length: 10 Owner: Charles Brown