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

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());
}
}

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.

I'm trying to understand the Building Pattern and I have trouble with the Director

I try to code a builder pattern for my better understanding. Mostly I relied on GOF and wikipedia.
So my Object is a house with required attribute area and some optional attributes (like windows, doors, rooms etc.)
I will show you the code. Now, I'm not really sure if its correct and I think I don't have a director? I don't get in which cases you need one and how it works.
This is my class house and the innerclass HouseBuilder
public class House {
//required
private final String area;
//optional
private int windows;
private int doors;
private int rooms;
//constructor with HouseBuilder
private House(HouseBuilder builder) {
this.windows = builder.windows;
this.doors = builder.doors;
this.rooms = builder.rooms;
}
public static class HouseBuilder {
//required
private String area;
//optional
private int windows;
private int doors;
private int rooms;
//constructor with required attributes
HouseBuilder(String area) {
this.area = area;
}
//optional attributes
public HouseBuilder windows(int windows) {
this.windows = windows;
return this;
}
public HouseBuilder doors (int doors) {
this.doors = doors;
return this;
}
//function for building
public Housebuild() {
return new House(this);
}
}
Now, I just got a class demo where I can build a house like that:
House house = new House.HouseBuilder("Downtown")
.doors(3).windows(2).build();
But this is not a director like in the books. Is my idea even correct? And why is that better than just using setters?
Thanks!
Your example illustrates classic builder. Director is something like an abstract builder, and in practise it is rarely used because the client class can handle that perfectly well. Example of a director in your case would be:
public class House
{
public final String area;
public windows;
public int doors;
public int rooms;
}
interface HouseBuilder
{
public HouseBuilder area();
public HouseBuilder windows();
public HouseBuilder doorsors();
public HouseBuilder rooms();
public House build();
}
public static class DowntownHouseBuilder implements HouseBuilder
{
House downtownHouse = new House();
public HouseBuilder area()
{
downtownHouse.area = "Downtown";
}
public HouseBuilder windows()
{
downtownHouse.windows = 3;
return this;
}
public HouseBuilder doors()
{
downtownHouse.doors = 2;
return this;
}
public HouseBuilder rooms()
{
downtownHouse.rooms = 2;
return this;
}
public House build()
{
return downtownHouse;
}
}
public static class VilaBuilder implements HouseBuilder
{
House vila new House();
public HouseBuilder area()
{
vila.area = "Downtown";
}
public HouseBuilder windows()
{
vila.windows = 24;
return this;
}
public HouseBuilder doors()
{
vila.doors = 5;
return this;
}
public HouseBuilder rooms()
{
downtownHouse.rooms = 10;
return this;
}
public House build()
{
return vila;
}
}
class Driector
{
private HouseBuilder houseBuilder;
public Driector(HouseBuilder houseBuilder)
{
this.houseBuilder = houseBuilder;
}
public House buildHouse()
{
return this.houseBuilder.area()
.windows()
.doors()
.rooms()
.buid();
}
}
class HouseConstruction
{
public static void main(String[] args)
{
Director director = new Director(new VilaBuilder());
House house = director.buildHouse();
System.out.println("Builder constructed: "+ house);
}
}
Hope this helps clarify what is a Director in Builder pattern.

Accessing object properties when object is created in main method via other class constructor

I have 3 classes Test, Factory and TV - Factory is aimed to create TVs (classes are included below).
How can I access or manipulate properties of new TV, that was created in main method of Test Class (via TV class constructor invoked by Factory method in Test class).
public class TV {
private int productionYear;
private double price;
public TV (int productionYear, double price){
this.productionYear = productionYear;
this.price = price;
}
}
public class Factory {
public static int numberOfTV = 0;
public void produceTV(int a, double b){
TV tv = new TV(a,b);
numberOfTV++;
}
public void printItems(){
System.out.println("Number of TVs is: " + numberOfTV);
}
}
public class Test {
public static void main(String[] args) {
Factory tvFactory = new Factory();
tvFactory.produceTV(2001, 399);
tvFactory.printItems();
}
}
public class TV {
private int productionYear;
private double price;
public TV(int productionYear, double price) {
this.productionYear = productionYear;
this.price = price;
}
public int getProductionYear() {
return productionYear;
}
public void setProductionYear(int productionYear) {
this.productionYear = productionYear;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
public class Factory {
public static int numberOfTV = 0;
public TV produceTV(int a, double b) {
TV tv = new TV(a, b);
numberOfTV++;
return tv;
}
public void printItems() {
System.out.println("Number of TVs is: " + numberOfTV);
}
}
public class Test {
public static void main(String[] args) {
Factory tvFactory = new Factory();
TV tv = tvFactory.produceTV(2001, 399);
tvFactory.printItems();
// Do manipulation with tv reference here
}
}
Your problem is that your Factory class produces TVs but never ships them anywhere.
In order to manipulate an object, you need a reference to it. Simply have the produceTV method return the TV that is produced.
public TV produceTV(int a, double b){
numberOfTV++;
return new TV(a,b);
}
Right now you create a reference that is never used; most likely the compiler will eliminate the TV object creation.

Passing a Collection of Java Beans as DataSource to Jasper, How to design this in ireports

I need to design a report, that displays the data from a collection(Say List). This list contains multiple POJOs.
The POJOs are populated by the data access layer of the application. How do I design a report template for this requirement in iReports?
Use JRBeanCollectionDataSource for your report.
Ok! Found the answer. The steps are as below.
Compile the bean classes and create a JAR file. This needs to have the complete package
Add this jar to the LIB folder in ireports
Create a factory/wrapper class that has a createBeanCollection method that populates a collection
Use this class's top level package as the class path in ireports
Use this class as the JavaBean datasource with the method.
Once all this is done, create a report with the new datasource and in report query, give the FQN on the Java bean and add the desired field.
BankDetailsList list = new BankDetailsList();
ArrayList<BankDetails> lst = list.getDataBeanList();
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(lst);
Here BankDetails is a POJO
public class BankDetails {
public String bank_name;
public Account account;
public String custodian_account;
public String custodian_name;
public String agreement_type;
public double exposure;
public double collateral;
public double independant_amount;
public double net_exposure;
BankDetails(String b_name, Account acc, String cust_account,
String cust_name, String agr_type, double expo, double collat,
double independant_amt, double net_exp) {
this.bank_name = b_name;
this.account = acc;
this.custodian_account = cust_account;
this.custodian_name = cust_name;
this.agreement_type = agr_type;
this.exposure = expo;
this.collateral = collat;
this.independant_amount = independant_amt;
this.net_exposure = net_exp;
}
public String getBank_name() {
return bank_name;
}
public void setBank_name(String bank_name) {
this.bank_name = bank_name;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public String getCustodian_account() {
return custodian_account;
}
public void setCustodian_account(String custodian_account) {
this.custodian_account = custodian_account;
}
public String getCustodian_name() {
return custodian_name;
}
public void setCustodian_name(String custodian_name) {
this.custodian_name = custodian_name;
}
public String getAgreement_type() {
return agreement_type;
}
public void setAgreement_type(String agreement_type) {
this.agreement_type = agreement_type;
}
public double getExposure() {
return exposure;
}
public void setExposure(double exposure) {
this.exposure = exposure;
}
public double getCollateral() {
return collateral;
}
public void setCollateral(double collateral) {
this.collateral = collateral;
}
public double getIndependant_amount() {
return independant_amount;
}
public void setIndependant_amount(double independant_amount) {
this.independant_amount = independant_amount;
}
public double getNet_exposure() {
return net_exposure;
}
public void setNet_exposure(double net_exposure) {
this.net_exposure = net_exposure;
}
}
Account POJO:
public class Account {
public int account_id;
public String account_name;
Account(int acc_id, String acc_name){
this.account_id = acc_id;
this.account_name = acc_name;
}
public int getAccount_id() {
return account_id;
}
public void setAccount_id(int account_id) {
this.account_id = account_id;
}
public String getAccount_name() {
return account_name;
}
public void setAccount_name(String account_name) {
this.account_name = account_name;
}
}

Categories