TestingDocs.com
Software Testing website
  • Automation
    • Selenium
    • JBehave Framework
  • Tutorials
    • MySQL Tutorials
    • Testlink
    • Maven
    • Git
  • IDEs
    • IntelliJ IDEA
    • Eclipse
  • Flowcharts
    • Flowgorithm
    • Raptor
  • About

Java Tutorials

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

Array of Objects Java

 

—

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/

Related Posts

Download Greenfoot Windows

Java Tutorials /

Download & Install Greenfoot on Windows

Java Tutorials /

Java Static Code Analysis

Java Tutorials /

Java Testing Tools

Java Tutorials /

Handle Multiple Exceptions in Java

Exceptions_In_Java

Java Tutorials /

Exceptions in Java Programs

‹ Introduction to Java Language› Java Program Structure

Recent Posts

  • Update draw.io on Windows
  • Install RAPTOR Avalonia on CentOS
  • Download RAPTOR Avalonia Edition on Windows
  • npm doctor command
  • Build & Run CLion Project
  • Create New CLion C Project on Windows
  • Configure CLion Toolchains on Windows
  • Launch CLion IDE on Windows
  • Activate CLion IDE
  • CLion IDE for C/C++ Development

Back to Top

Links

  • Contact
  • Privacy Policy
  • Cookie Policy

www.TestingDocs.com