An array itself is a special kind of object
An array may contain data of primitive data type (int, double, char, boolean, etc.)
Array must only contain data of single data type
Array may also contain Objects (of the same type)
public class Rectangle {
private double length;
private double width;
public Rectangle(double l, double w) {
length = l;
width = w;
}
public double getLength() {
return length;
}
public void setLength(double length) {
this.length = length;
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
this.width = width;
}
public double getArea(){
return length * width;
}
public double getPerimeter(){
return 2 * (length + width);
}
}
//array of rectangle of 3 elements
Rectangle[] r = new Rectangle[3];
//assigning Rectangles to indexes 0, 1, and 2
r[0] = new Rectangle(2.3, 4.2);
r[1] = new Rectangle(3.0, 5.0);
r[2] = new Rectangle(4.2, 8.0);
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" + "name=" + name + ", age=" + age + '}';
}
}
public class PersonsArray {
private Person[] people;
private int num;
private int count = 0;
public PersonsArray(int num) {
this.num = num;
people = new Person[this.num];
}
//adds Person p to the array
public void addPerson(Person p) {
if (count < people.length && p != null) {
people[count] = p;
count++;
System.out.println("Person is added successfully...");
}else{
System.out.println("You can not enter a null value");
}
}
//prints all p in people array
public void printPeople() {
for (Person p : people) {
System.out.println(p);
}
}
//returns oldest person on the array of people
public Person getOldest() {
Person p = new Person("", 0);
for (int i = 0; i < people.length; i++) {
if (people[i] != null && people[i].getAge() > p.getAge()) {
p = people[i];
}
}
return p;
}
}