Passing data of a variable to another class - java

EDITED to clarify further.
I'm trying to build a simple api which handles the CRUD operation on my simple MySQL database for my simple Ordering Web App. The api will then be used on Angular.
Basically, the conditions for the ordering system is that there would be a 5% off on selected orders, so that would be DiscountedBill job to calculate on how much it would be. Other items do not have the discount, so that would be for RegularBill job to calculate.
As I have understood on this diagram, OrderBill class will have to calculate on how much the TOTAL of ALL orders if the user has DiscountedBill and RegularBill orders on my system.
Would that be possible?
This is the main OrderBill class.
public class OrderBill {
private List<Order> orderList;
private CafeClerk clerk;
public OrderBill(CafeClerk clerk) {
this.clerk = clerk;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public CafeClerk getClerk() {
return clerk;
}
public void setClerk(CafeClerk clerk) {
this.clerk = clerk;
}
public double getTotalBill() {
// function here to add the computed data of both DiscountedBill + RegularBill
return 0;
}
}
RegularBill class –
public class RegularBill extends OrderBill {
public RegularBill(CafeClerk clerk) {
super(clerk);
}
double totalRegBill = 0.0;
#Override
public double getTotalBill() {
for (Order order : super.getOrderList()) {
totalRegBill += (order.getPrice());
}
return totalRegBill;
}
public double getTotalRegBill() {
return totalRegBill;
}
public void setTotalRegBill(double totalRegBill) {
this.totalRegBill = totalRegBill;
}
}
DiscountedBill class –
public class DiscountedBill extends OrderBill {
public DiscountedBill(CafeClerk clerk) {
super(clerk);
}
final double DISCOUNT = 0.05;
double totalDiscBill = 0.0;
#Override
public double getTotalBill() {
for (Order order :super.getOrderList()) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
public double getTotalDiscBill() {
return totalDiscBill;
}
public void setTotalDiscBill(double totalDiscBill) {
this.totalDiscBill = totalDiscBill;
}
}

I am not sure if I understand the purpose correctly, but if you want to sum up the DiscountedBill and RegularBill in OrderBill, don't you rather need a structure like this?
public class OrderBill {
private List<Order> orderList;
private CafeClerk clerk;
private RegularBill regularBill;
private DiscountedBill discountedBill;
public OrderBill(CafeClerk clerk) {
this.clerk = clerk;
}
public List<Order> getOrderList() {
return orderList;
}
public void setOrderList(List<Order> orderList) {
this.orderList = orderList;
}
public CafeClerk getClerk() {
return clerk;
}
public void setClerk(CafeClerk clerk) {
this.clerk = clerk;
}
public double getTotalBill() {
return regularBill.getTotalBill(orderList) + discountedBill.getTotalBill(orderList);
}
}
public class RegularBill {
public RegularBill() {}
double totalRegBill = 0.0;
public double getTotalBill(List<Order> orders) {
for (Order order : orders) {
totalRegBill += (order.getPrice());
}
return totalRegBill;
}
public double getTotalRegBill() {
return totalRegBill;
}
public void setTotalRegBill(double totalRegBill) {
this.totalRegBill = totalRegBill;
}
}
public class DiscountedBill {
public DiscountedBill() { }
final double DISCOUNT = 0.05;
double totalDiscBill = 0.0;
public double getTotalBill(List<Order> orders) {
for (Order order : orders) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
public double getTotalDiscBill() {
return totalDiscBill;
}
public void setTotalDiscBill(double totalDiscBill) {
this.totalDiscBill = totalDiscBill;
}
}
Of course, enhancing this solution is necessary. But that may be a hint already.
You can then implement an interface with getTotalBill() method.

If you need to recreate this diagram, then my hint is that you make OrderBill abstract, and getTotalBill() interests you only in the RegularBill and DiscountedBill.
You cannot really add up these two classes inside of OrderBill with the given structure.

If I understand that right, you could do:
public DiscountedBill(RegularBill bill) {
this.setOrderList(bill.getOrderList);
this.setClerk(bill.getClerk());
}
#Override
public double getTotalBill() {
for (Order order :this.getOrderList()) {
totalDiscBill += (order.getPrice() - DISCOUNT);
}
return totalDiscBill;
}
Notice: If I get it right, you are just subtracting 0.05 in total not in %, mabbe it should be:
#Override
public double getTotalBill() {
for (Order order :this.getOrderList()) {
totalDiscBill += (order.getPrice() - (order.getPrice() * DISCOUNT));
}
return totalDiscBill;
}
But it is just a guess what I think what you trying to archieve.

Related

How to check between two subclasses which one has been called when creating an instance?

I'm trying to create a "bank account" with its operations. Some of them are:
bank addition : class Ajout
bank withdrawal : class Retrait
There are the bank balance variable named solde and amount named montant
The AjoutOuRetrait class is the mother class (means AdditionOrWithdrawal)
Now what I expect in my main class is the following:
c1.operation(new Ajout(750, new Date(01,01,2017)));
c1.operation(new Retrait(50, new Date(05,03,2017)));
System.out.println(c1.getSolde()); // result -> 700
public class AjoutOuRetrait {
public int montant;
public Date date;
public AjoutOuRetrait(int montant, Date d) {
this.montant = montant;
this.date = d;
}
public class CompteBancaire {
private String id;
private Banque banque;
private int solde;
public CompteBancaire(String id, Banque b) {
this.id = id;
this.banque = b;
}
public void operation(AjoutOuRetrait aor){
this.solde = aor.montant;
}
more the getters and setters that I omitted.
public class Retrait extends AjoutOuRetrait {
public Retrait(int montant, Date d) {
super(montant, d);
}
}
public class Ajout extends AjoutOuRetrait{
public Ajout(int montant, Date d) {
super(montant, d);
}
I was thinking on a way to differentiate (with conditional statement) which child class I call in argument of operation() method , whether it is Retrait (WithDrawal) -- or Ajout(Additional) ++
You might check the child type in operation like.
public void operation(AjoutOuRetrait aor){
if(aor instanceof Ajout) {
this.solde += aor.montant;
} else if (aor instanceof Retrait) {
this.solde -= aor.montant;
}
}
or split them
public void operation(Ajout a){
this.solde += a.montant;
}
public void operation(Retrait r){
this.solde -= r.montant;
}
Also you might get the value used as right operand of your operation like
public class AjoutOuRetrait {
public int getValue() {
return this.montant;
}
}
public class Retrait {
#Override
public int getValue() {
return -this.montant;
}
}
public void operation(AjoutOrRetrait aor) {
this.solde += aor.getValue();
}

Using arbitrary number of classes

I would appreciate any help in solving the following question.
Design and implement a subclass of GenericOrder called ComputerPartyOrder that takes an arbitrary number of different classes of ComputerPart objects, Peripheral objects, Cheese objects, Fruit objects and Service objects.
here is the code for Product class and GerericOrder class.
abstract class Product {
protected float price;
// return the price of a particular product
abstract float price();
//public getType() {
//
//}
}
//------------------------------------------------------------
class ComputerPart extends Product {
public ComputerPart(float p) {
price = p;
}
public float price() { return price; }
}
class Motherboard extends ComputerPart {
protected String manufacturer;
public Motherboard(String mfg, float p) {
super(p);
manufacturer = mfg;
}
public String getManufacturer() { return manufacturer; }
}
class RAM extends ComputerPart {
protected int size;
protected String manufacturer;
public RAM(String mfg, int size, float p) {
super(p);
this.manufacturer = mfg;
this.size = size;
}
public String getManufacturer() { return manufacturer; }
}
class Drive extends ComputerPart {
protected String type;
protected int speed;
public Drive(String type, int speed, float p) {
super(p);
this.type = type;
this.speed = speed;
}
public String getType() { return type; }
public int getSpeed() { return speed; }
}
class Peripheral extends Product {
public Peripheral(float p) {
price = p;
}
public float price() { return price; }
}
class Printer extends Peripheral {
protected String model;
public Printer(String model, float p) {
super(p);
this.model = model;
}
public String getModel() { return model; }
}
class Monitor extends Peripheral {
protected String model;
public Monitor(String model, float p) {
super(p);
this.model = model;
}
public String getModel() { return model; }
}
class Service extends Product {
public Service(float p) {
price = p;
}
public float price() { return price; }
}
class AssemblyService extends Service {
String provider;
public AssemblyService(String pv, float p) {
super(p);
provider = pv;
}
public String getProvider() { return provider; }
}
class DeliveryService extends Service {
String courier;
public DeliveryService(String c, float p) {
super(p);
courier = c;
}
public String getCourier() { return courier; }
}
//-------------------------------------------------------
class Cheese extends Product {
public Cheese(float p) {
price = p;
}
public float price() { return price; }
}
class Cheddar extends Cheese {
public Cheddar(float p) {
super(p);
}
}
class Mozzarella extends Cheese {
public Mozzarella(float p) {
super(p);
}
}
class Fruit extends Product {
public Fruit(float p) {
price = p;
}
public float price() { return price; }
}
class Apple extends Fruit {
public Apple(float p) {
super(p);
}
}
class Orange extends Fruit {
public Orange(float p) {
super(p);
}
}
GenericOrder:
import java.util.ArrayList;
import java.util.List;
public abstract class GenericOrder<T> extends Product {
private static long counter = 1;
private final long id = counter++;
private List<T> Item;
public GenericOrder() {
Item = new ArrayList<T>();
}
public long getid() {
return id;
}
public void addItem(T newItem) {
Item.add(newItem);
}
public List<T> getItem() {
return Item;
}
public void setItem(List<T> Item) {
this.Item = Item;
}
}
EDIT: Code so far
public abstract class ComputerPartyOrder extends GenericOrder {
GenericOrder GOrder = new GenericOrder() {
#Override
float price() {
return 0;
}
};
public void input(Product newitem) {
GOrder.addItem(newitem);
}
public void output() {
System.out.println(GOrder.getItem());
}
}
You have the right idea, but GenericOrder does not need a type parameter T. Instead, you can set the type of Item to Product (the superclass of all the different types of products).
public abstract class GenericOrder extends Product {
private static long counter = 1;
private final long id = counter++;
private List<Product> Item;
public GenericOrder() {
Item = new ArrayList<Product>();
}
public long getid() {
return id;
}
public void addItem(Product newItem) {
Item.add(newItem);
}
public List<Product> getItem() {
return Item;
}
public void setItem(List<Product> Item) {
this.Item = Item;
}
}
You will still be able to call addItem with any instance of a subclass of Product.
I would also suggest renaming Item to item, uppercase names are usually used for types, not variables.

get some object of one class and use in another class

I want to use some object of one class and use in other class,but i can not
for example :
class 1:
public class Value {
private double radious;
private double lenght;
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
}
question : how can I use just radious of class 1 in class 2???
class 2:
public class calculateArea
{
private Value value;
public double area()
{
return 3.14*radious*radious;
}
}
Create getters for both the values and access them in your second class.
Something like
public double getRadious() {
return this.radious;
}
public double getLenght() {
return this.lenght;
}
When working on OOP, ask yourself what code goes where and how many classes you have to make?
For your scenario, you can use aggregation or composition which is to declare the object of one class in another and then you can call the methods of the declared object using dot notation with getter setter methods. So it will go like this.
public class Value
{
private double radious;
private double lenght;
public void setRadious(double radious)
{
this.radious = radious;
}
public double getRadious() {
return this.radious;
}
public double getLenght() {
return this.lenght;
}
public void setLenght(double lenght)
{
this.lenght = lenght;
}
}
Class # 2
public class calculateArea
{
private Value value = new Value();
public calculateArea(double rad) {
value.setRadius(rad);
}
public double area()
{
return 3.14*value.getRadious()*value.getRadious();
}
}
Also, you need to set the value of radius before using it.
Make a getter Method for radious:
public double getRadious(){
return radious;
}
In the "Main Class":
Value v = new Value();
v.setRadious(2.5);/*Set the Radious value*/
public double area()
{
return 3.14*v.getRadious()*v.getRadious();
}
Add getters to class Value.
public class Value {
public double radious;
public double lenght;
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
public double getLenght() {
return this.lenght;
}
public double getRadious() {
return this.radious;
}
}
Make an instance of class 1
public class calculateArea{
public Value;
calculateArea(){
value = new Value();
}
public double area(){
value.setRadious(2.34);//or set ACCORDINGLY
return 3.14 * value.radious * value.radious;
}
}
Declare getters and setters for Value-class:
public class Value {
private double radious;
private double lenght;
public Value(double radious, double length) {
this.radious = radious;
this.length = length;
}
public void setRadious(double radious) {
this.radious = radious;
}
public void setLenght(double lenght) {
this.lenght = lenght;
}
public double getRadious() {
return this.radious;
}
public double getLength() {
return this.length;
}
}
Instantiate the object with some variables:
Value value = new Value(2.0,3.0);
Add Constructor to CalculateArea class:
public class calculateArea {
private Value value;
public calculateArea(Value value) {
this.value = value;
}
public double area()
{
return 3.14*value.getRadious()*value.getRadious();
}
}
Instantiate:
calculateArea cArea= new calculateArea(value);
And print result to console in main() method:
System.out.println(cArea.area());

How to iterate over generic list

I have a class in that I take one list of generic type. Now I am trying to iterate over that list to get the value of that class. In getOrderAmount() method I trying to iterate.
#Document(collection = Cart.FIELDS.COLLECTION)
public class Cart extends BaseOrderEntity {
public interface FIELDS extends BaseOrderEntity.FIELDS {
String COLLECTION = "cart";
String LIST_ORDERS = "orderList";
String CART_TYPE = "cartType";
}
#Field(value = FIELDS.LIST_ORDERS)
private List<T> orderList;
#Field(value = FIELDS.CART_TYPE)
private Integer cartType;
public List<T> getOrderList() {
return orderList;
}
public void setOrderList(List<T> orderList) {
this.orderList = orderList;
}
public Integer getCartType() {
return cartType;
}
public void setCartType(Integer cartType) {
this.cartType = cartType;
}
#Override
public RefCollectionType getRefCollectionType() {
if (T.class.getClass() == FoodItemOrderDetails.class.getClass()) {
return RefCollectionType.FOOD;
} else if (T.class.getClass() == LaundryItemOrderDetails.class.getClass()) {
return RefCollectionType.LAUNDRY;
} else if (T.class.getClass() == HousekeepingItemOrderDetails.class.getClass()) {
return RefCollectionType.HOUSEKEEPING;
}
return RefCollectionType.FOOD;
}
#Override
public double getOrderAmount() {
double totalfoodOrderAmount = 0.0;
for (FoodItemOrderDetails foodItem : orderList) {
totalfoodOrderAmount = totalfoodOrderAmount + (foodItem.getPrice() * foodItem.getQuantity());
}
return totalfoodOrderAmount;
}
}
The generic classes are here.
FoodItemOrderDetails
LaundryItemOrderDetails
HousekeepingItemOrderDetails
You should have an interface like OrderDetails which should have 2 methods getQuantity() and getPrice(). Now implement that interface in FoodItemOrderDetails,
LaundryItemOrderDetails, HousekeepingItemOrderDetails.
for (OrderDetails item : orderList) {
totalAmount = totalAmount + (item .getPrice() * item.getQuantity());
}
Your Interface should looks like below.
interface OrderDetails {
Double getPrice();
Integer getQuantity();
}
Your classes should look like below.
class FoodItemOrderDetails implements OrderDetails {
#Override
public Double getPrice() {
// return the price for FoodItem
return null;
}
#Override
public Integer getQuantity() {
// return the Quantity for FoodItem
return null;
}
}
You can use Java-8 stream.
List<OrderDetails> details = new ArrayList<>();
double total = details.stream().mapToDouble(e -> e.getPrice() * e.getQuantity()).sum();

Constructing in Java using variables from a different class [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
So i have 4 classes of a car The Engine, The transmission, The Chassis and the Car itself each are coded as follows:
public class Chassis {
public double m_Cprice;
public Chassis(double m_Cprice) {
this.m_Cprice = m_Cprice;
}
public double getChassisPrice() {
return m_Cprice;
}
public void setChassisPrice(double m_Cprice){
this.m_Cprice = m_Cprice;
}
}
For the Chassis:
public class Transmission {
public double m_Tprice;
public Transmission(double m_Tprice){
this.m_Tprice = m_Tprice;
}
public double getTransmissionPrice() {
return m_Tprice;
}
public void setTransmissionPrice(double m_Tprice){
this.m_Tprice = m_Tprice;
}
}
For the Engine:
public class Engine {
public double m_Eprice;
public Engine(double m_Eprice){
this.m_Eprice = m_Eprice;
}
public double getEnginePrice() {
return m_Eprice;
}
public void setEnginePrice(double m_Eprice){
this.m_Eprice = m_Eprice;
}
}
And finally for the Car:
public final class Car {
public double m_baseprice;
public Chassis m_Cprice;
public Engine m_Eprice;
public Transmission m_Tprice;
public double getBaseprice() {
return m_baseprice;
}
public void setBasePrice(double m_baseprice){
this.m_baseprice = m_baseprice;
}
public Car(double Baseprice,double Chassis, double Engine, double Transmission) {
setBasePrice(Baseprice);
m_Cprice = new Chassis(Chassis);
m_Eprice = new Engine(Engine);
m_Tprice = new Transmission(Transmission);
}
public Chassis getM_Cprice() {
return m_Cprice;
}
public void setM_Cprice(Chassis m_Cprice) {
this.m_Cprice = m_Cprice;
}
public Engine getM_Eprice() {
return m_Eprice;
}
public void setM_Eprice(Engine m_Eprice) {
this.m_Eprice = m_Eprice;
}
public Transmission getM_Tprice() {
return m_Tprice;
}
public void setM_Tprice(Transmission m_Tprice) {
this.m_Tprice = m_Tprice;
}
When i try to call the constructor for this app, everything works fine with no errors in my code, however when i ask to output anything nothing is output at all meaning i cannot properly construct my car using the boundaries within the constructor which are new Car(3000, 500, 1000, 2000) making the app not work correctly although no errors are there to point me in the correct direction.
Please leave off that awful "m_" prefix for member variables. It is horrible to read.
You need to learn more Java. First step: override toString() in all your classes to output the price. What you're seeing is the default output: the reference value for each class.
Double is not a good idea for money. Since you're dealing with big ticket items here, I'd recommend leaving off the cents and sticking to integers and whole dollars.
public class Engine {
private int price;
public Engine(int price) {
this.setPrice(price);
}
public int getPrice() {
return price;
}
public void setPrice(int price){
if (price <= 0) throw new IllegalArgumentException("price must be positive");
this.price = price;
}
public String toString() {
return String.format("price: %d", this.price);
}
}
I know you're a beginner, but this design is crying out for an interface and a Composite pattern:
public interface Sellable {
int getPrice();
void setPrice(int price);
}
Now your Car can be considered a collection of Sellable instances. Its price will be a sum of all the Sellables.
The overall structure of your code is not very good. I suggest the following:
public class CarPart {
private double price;
public Part(final double price) {
this.price = price;
}
public double getPrice() {
return price;
}
public void setPrice(final double price) {
this.price = price;
}
#Override
public String toString() {
return "Price = " + price;
}
}
public class Engine extends CarPart {
public Engine(final double price) {
super(price);
}
}
public class Chassis extends CarPart {
public Chassis(final double price) {
super(price);
}
}
public class Transmission extends CarPart {
public Transmission(final double price) {
super(price);
}
}
public class Car {
private double totalPrice;
private Chassis chassis;
private Engine engine;
private PTransmission transmission;
public Car(final double totalPrice, final Chassis chassis, final Engine engine, final Transmission transmission) {
this.totalPrice = totalPrice;
this.chassis = chassis;
this.engine = engine;
this.transmission = transmission;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(final double totalPrice) {
this.totalPrice = totalPrice;
}
public Chassis getChassis() {
return chassis;
}
public void setChassis(final Chassis chassis) {
this.chassis = chassis;
}
public Engine getEngine() {
return engine;
}
public void setEngine(final Engine engine) {
this.engine = engine;
}
public Transmission getTransmission() {
return transmission;
}
public void setTransmission(final Transmission transmission) {
this.transmission = transmission;
}
}
Now you'll be able to use the application:
public class Main {
public static void main(String[] args) {
final Chassis chassis = new Chassis(2000);
final Engine engine = new Engine(3000);
final Transmission transmission = new Transmission(4000);
final Car car = new Car(1000, chassis, engine, transmission);
System.out.println(chassis.toString());
}
}

Categories