An Example of a Pass by Reference Value - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

An Example of a Pass by Reference Value

Demo Code

class Product {/*from   w  ww .j  a v a  2  s  .  co  m*/
  public String model = "Unknown";
  public int year = 2000;
  public double price = 0.0;
}
public class Main {
  public static void main(String[] args) {
    // Create a Car object and assign its reference to myCar
    Product myCar = new Product();

    // Change model, year and price of Car object using myCar
    myCar.model = "Civic";
    myCar.year = 2000;
    myCar.price = 9600.0;

    System.out.println("#1: model = " + myCar.model + ", year = " + myCar.year
        + ", price = " + myCar.price);

    Main.test(myCar);

    System.out.println("#4: model = " + myCar.model + ", year = " + myCar.year
        + ", price = " + myCar.price);
  }
  public static void test(Product xyCar) {
    System.out.println("#2: model = " + xyCar.model + ", year = " + xyCar.year
        + ", price = " + xyCar.price);
    // Let us make xyCar refer to a new Car object
    xyCar = new Product();
    System.out.println("#3: model = " + xyCar.model + ", year = " + xyCar.year
        + ", price = " + xyCar.price);
  }
}

Result


Related Tutorials