Java constructor confusion, what goes where? -


unsure should placed constructor , should field, notice can add things initialized without them having in constructor. here 2 examples, i'm unsure best use , reasons behind it.

example 1:

public class purchaseorder {     private string date;     private string customerid;     private string productcode;     private int quantity;     private int discountrate;     private int priceperunit;     private customerdetails customer; // part i'm changing      public purchaseorder(orderdate date, string id,             product product, int quantity) {         this.discountrate = customer.getdiscountrate();         this.date = date.getdate();         this.customerid = customer.getcustomerid();         this.productcode = product.getproductcode();         this.quantity = quantity;         this.priceperunit = product.getpriceperunit();     } 

example 2:

public class purchaseorder {     private string date;     private string customerid;     private string productcode;     private int quantity;     private int discountrate;     private int priceperunit;     public purchaseorder(orderdate date, customerdetails customer,             product product, int quantity) {         this.discountrate = customer.getdiscountrate();         this.date = date.getdate();         this.customerid = customer.getcustomerid();         this.productcode = product.getproductcode();         this.quantity = quantity;         this.priceperunit = product.getpriceperunit();     } 

notice can put customerdetails customer in constructor or have variable. if it's in constructor means if object made of class must contain information of customerdetails. both work fine. what's best option , reason it?

what pass in constructor parameter has been made in class object such as

customerdetails customerinconstructor = new customerdetails(); 

then go

purchaseorder purchase = new purchaseorder(customerinconstructor, otherparameters) 

if don't wanna pass in object made previous class , instead make new 1 class make variable shown in first example.

private customerdetails customer; 

constructors ways take variables other classes main class , use variables make methods affect them or add things them. hope kinda helped, have day!


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -