0
import java.util.*;

public class MainClass {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       Products p1 = new Products(100,"Genius Keyboard",450.50,10);
       Products p2 = new Products(200,"Genius Mouse",480.00,10);
       Products p3 = new Products(300,"Monitor",5000.00,50);

        ArrayList<Products> list = new ArrayList<Products>();
            list.add(p1);
            list.add(p2);
            list.add(p3);

           Iterator<Products> itr = list.iterator();
                while(itr.hasNext()){
            System.out.println(itr.next());
                }

    }

public class Products {
        int productCode;
    String productName;
    double productPrice;
    int productQuantity;

  Products(int productCode,String productName,double productPrice,int productQuantity){
      this.productCode = productCode;
      this.productName = productName;
      this.productPrice = productPrice;
      this.productQuantity = productQuantity;

}

}
2
Contributors
1
Reply
19
Views
1 Month
Discussion Span
Last Post by JamesCherrill
1

println works by calling toString() on each of its arguments in order to get something printable. All classes inherit a toString() from Object, but all that does is to return the class and hash of the object. Thats what line 21 above will do.
You should always override toString in any class you define. It should return a String that is a useful representation of the instance's values. println will then use that when you ask it to print a Products.

ps Minor point: class names should be singular - each instance represents one Product.

Edited by JamesCherrill: Spelling

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.