Modifying the States of Array Elements of an Array Parameter Inside a Method - Java Object Oriented Design

Java examples for Object Oriented Design:Method Parameter

Description

Modifying the States of Array Elements of an Array Parameter Inside a Method

Demo Code

class Item {/*from  w  w  w. j a  v  a2s.  c  om*/
  private double price;
  private String name;

  public Item (String name, double initialPrice) {
    this.name = name;
    this.price = initialPrice;
  }

  public double getPrice() {
    return this.price;
  }

  public void setPrice(double newPrice ) {
    this.price = newPrice;
  }

  public String toString() {
    return "[" + this.name + ", " + this.price + "]";
  }
}
public class Main {
  public static void main(String[] args) {
    Item[] myItems = {new Item("Pen", 25.11), new Item("Pencil", 0.10)};
    System.out.println("Before method call #1:" + myItems[0]);
    System.out.println("Before method call #2:" + myItems[1]);

    // Call the method passing the array of Item
    tryStateChange(myItems);

    System.out.println("After method call #1:" + myItems[0]);
    System.out.println("After method call #2:" + myItems[1]);
  }

  public static void tryStateChange(Item[] allItems) {
    if (allItems != null && allItems.length > 0) {
      allItems[0].setPrice(1.38);
    }
  }
}

Result


Related Tutorials