Advertisement
tvdhout

Getting / setting by value / reference

May 8th, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. package com.tvdhout;
  2.  
  3. public class Main {
  4.  
  5.     public static void main(String[] args) {
  6.  
  7.         Car car20 = new Car(20);
  8.         Person thijs = new Person("Thijs", car20);
  9.  
  10.         Car thijsCar = thijs.getCar();
  11.         thijsCar = new Car(9000);
  12.         System.out.println(thijsCar);  // prints Car{serialNr=9000}
  13.         System.out.println(thijs.getCar());  // prints Car{serialNr=20}
  14.         // So replacing the object thijsCar we got with a getter does not update the Car in the Person object
  15.         // For that we need a setter
  16.  
  17.         thijsCar = thijs.getCar();
  18.         thijsCar.setSerialNr(9000);
  19.         System.out.println(thijs.getCar());  // prints Car{serialNr=9000}
  20.         // But we CAN change things inside thijsCar and it will update the Car in the Person object because
  21.         // That is the car that is referred to.
  22.     }
  23. }
  24.  
  25. class Person {
  26.     private String name;
  27.     private Car car;
  28.  
  29.     public Person(String name, Car car) {
  30.         this.name = name;
  31.         this.car = car;
  32.     }
  33.  
  34.     public Car getCar() {
  35.         return car;
  36.     }
  37. }
  38.  
  39. class Car {
  40.     private int serialNr;
  41.  
  42.     public Car(int serialNr) {
  43.         this.serialNr = serialNr;
  44.     }
  45.  
  46.     public int getSerialNr() {
  47.         return serialNr;
  48.     }
  49.  
  50.     public void setSerialNr(int serialNr) {
  51.         this.serialNr = serialNr;
  52.     }
  53.  
  54.     @Override
  55.     public String toString() {
  56.         return "Car{" +
  57.                 "serialNr=" + serialNr +
  58.                 '}';
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement