TurkuBasicOOPinJava / Week 4: Writing classes /15A Objects inside objects
KaiquanMah's picture
Create 15A Objects inside objects
0adf491 verified
raw
history blame
2.62 kB
It is often useful to store an object inside other objects -
in effect, using your own class as the type of an attribute defined in another class:
First, let's define the class Driver:
class Driver {
private String name;
private int birthYear;
public Driver(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
public String getName() {
return name;
}
public int getBirthYear() {
return birthYear;
}
}
Next, the class Car is defined, with one attribute of type Driver:
class Car {
private String brand;
private Driver driver;
public Car(String brand, Driver driver) {
this.brand = brand;
this.driver = driver;
}
public String getBrand() {
return brand;
}
public Driver getDriver() {
return driver;
}
}
If we have a Car object, and we want to know the name of the driver,
we can do that by first calling the method getDriver() and then calling the method getName() on the driver object:
public class TestClass {
public static void main(String[] args) {
Driver d = new Driver("Vebastian Settel", 1987);
Car car = new Car("Maston Artin", d);
System.out.println(car.getDriver().getName());
}
}
A class can also define a data structure to store objects from another class:
Let us first define the class Book:
class Book {
private String author;
private String name;
int pages;
public Book(String author, String name, int pages) {
this.author = author;
this.name = name;
this.pages = pages;
}
public String getAuthor() {
return author;
}
public String getName() {
return name;
}
public int getPages() {
return pages;
}
}
Then you define the Bookcase class, where you can store books.
In practice, the bookcase stores the books in a list.
In the Bookcase class, you can conveniently add a method that 'returns all books by a single author in a new list':
class Bookcase {
private ArrayList<Book> books;
// CONSTRUCTOR
public Bookcase() {
books = new ArrayList<>();
}
public void addBook(Book book) {
books.add(book);
}
public ArrayList<Book> authorsBooks(String authorName) {
ArrayList<Book> list = new ArrayList<Book>();
for (Book b: books) {
if (b.getAuthor().equals(authorName)) {
list.add(b);
}
}
return list;
}
}