Objects
Estimated time to read: 2 minutes
Object-Oriented Systems are built from objects. The objects are defined by the classes they are created from.
Objects¶
Objects are created at runtime from classes.
- Objects created by a particular class are said to be of that type. eg, the Car class is used to created objects of type Car
- Objects are often called instances of a class or just instances
- Creation of objects i also commonly called instantiation
In Java every object will have a reference value, so that it can be uniquely identified. These are not pointers, Java controls access to objects and ensures that programmers do not have direct access to memory as part of its security mechanisms.
Objects and Methods¶
From a class we can create as many instances / objects of it as we want, memory limitations aside, with each instance having its own set of attributes assigned.
Each instance / object will have the methods associated with its parent class assigned to it. The methods only act upon the attributes of that instance, each instance has its own private data.
Code Example¶
public class Car{
private String name;
public String getName(){
return name;
}
private int speed;
public int getSpeed(){
return speed;
}
public void setSpeed(int newSpeed){
speed = newSpeed;
}
private int gasoline;
private boolean engineState;
private LocalDate manufactured;
public LocalDate getManufactured(){
return manufactured;
}
public void setManufactured(LocalDate manufactured){
this.manufactured = manufactured
}
public int getAge(){
return Period.between(getManufactured(), LocalDate.now()).getYears();
}
public static void main(String[] args){
Car car54 = new Car(); // Create a new Car object, car54
car54.setName("Car 54"); // Name car54
car54.setSpeed(20); // Set car54's speed
car54.setManufactured(LocalDate.of(1961,9,17)); // Set car54's DoM
Car mach5 = new Car(); // Create a new Car object, mach5
mach5.setName("Mach V"); // Name mach5
mach5.setSpeed(20); // Set mach5's speed
mach5.setManufactured(LocalDate.of(1967,4,2)); // Set mach5's DoM
// Using an 'enhanced for loop' / a for-each loop. We're going to print out the information for each car.
// For the type Car, create a variable car - `for (Car car:`
// Create a new array using the type Car - ` new Car[]`
// Assign values to the array - `(car54, mach5)`
for (Car car: new Car[] (car54, mach5)) {
//Using printf, print out the information of the car we have iterated through
// printf is a 'format' string. We can used methods to fill in the variables that have been assigned.
// For this car, get it's Name, Age and Speed, then print the string
System.out.printf("%s is %d years old and is traveling at %d mph%n"),
car.getName(), car.getAge, car.getSpeed());
}
}
}