Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.tvdhout;
- public class Main {
- public static void main(String[] args) {
- Car car20 = new Car(20);
- Person thijs = new Person("Thijs", car20);
- Car thijsCar = thijs.getCar();
- thijsCar = new Car(9000);
- System.out.println(thijsCar); // prints Car{serialNr=9000}
- System.out.println(thijs.getCar()); // prints Car{serialNr=20}
- // So replacing the object thijsCar we got with a getter does not update the Car in the Person object
- // For that we need a setter
- thijsCar = thijs.getCar();
- thijsCar.setSerialNr(9000);
- System.out.println(thijs.getCar()); // prints Car{serialNr=9000}
- // But we CAN change things inside thijsCar and it will update the Car in the Person object because
- // That is the car that is referred to.
- }
- }
- class Person {
- private String name;
- private Car car;
- public Person(String name, Car car) {
- this.name = name;
- this.car = car;
- }
- public Car getCar() {
- return car;
- }
- }
- class Car {
- private int serialNr;
- public Car(int serialNr) {
- this.serialNr = serialNr;
- }
- public int getSerialNr() {
- return serialNr;
- }
- public void setSerialNr(int serialNr) {
- this.serialNr = serialNr;
- }
- @Override
- public String toString() {
- return "Car{" +
- "serialNr=" + serialNr +
- '}';
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement