Site icon TestingDocs.com

Array of Objects in Java

Overview

In this post, we will learn how to construct an array of objects and iterate them in Java. Let’s consider an interface JuicyFruit to denote if the object is juice able or not. The interface has the juice() method. One of the usages of an interface is to denote an object that has specific characteristics. Any class that implements JuicyFruit should provide implementation to the method juice() that is declared in the interface.

 

JuicyFruit

public interface JuicyFruit {
  public void juice();
}

Now, we will define Fruit objects that implements JuicyFruit interface.

Fruit.java

public class Fruit implements JuicyFruit {
    private String name;

    //Constructor
    public Fruit(String name) {
        this.name=name;
    }

    @Override
    public void juice() {
        System.out.println("Juicing " + toString());
    }

    @Override
    public String toString() {
        return name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

Now, will simulate a juice shop with an array of Fruit objects. We will construct 3 fruit objects.

JuicyFruit[] fruits = {orange, apple,grape};

FruitShop.java

The fruits is an array of JuicyFruit objects. To iterate the objects we have used an enhanced foreach loop.

public class FruitShop {

    public static void main(String[] args) {
        // Simulate Fruit Shop
        JuicyFruit orange = new Fruit("Orange");
        JuicyFruit apple = new Fruit("Apple");
        JuicyFruit grape = new Fruit("Grapes");
        JuicyFruit[] fruits = {orange, apple,grape};

        for (JuicyFruit fruit: fruits) {
            fruit.juice();
        }
    }
}

Sample Output

 

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version