Spaces:
Running
Running
File size: 2,616 Bytes
0adf491 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
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;
}
}
|