Extend and print from an abstract class - java

Ok guys I've got an assignment that has a abstract class 'Order' and three other classes that extend it 'OverseasOrder', 'RegularOrder', and 'NonProfitOrder'
Here is my abstract class:
public abstract class Order {
protected String location;
protected double price;
public Order(double price, String location){
}
public abstract double calculateBill();
public String getLocation() {
return location;
}
public double getPrice() {
return price;
}
public abstract String printOrder(String format);
}
and here is my 'NonProfitOrder':
public class NonProfitOrder extends Order {
public NonProfitOrder(double price, String location) {
super(price, location);
}
public double calculateBill() {
double bill;
bill = price;
return bill;
}
public String printOrder(String format){
String Long = "Non-Profit Order" + "\nLocation: " + getLocation() + "\nTotal Price: " + getPrice();
return Long;
}
}
I'm taking it step by step to make sure everything is working so this is the only classes I have written so far. The problem I having is when I test something like
public class OrderTester {
public static void main(String[] args) {
Order o;
o = new NonProfitOrder(2000.0, "NY");
System.out.println(o.printOrder("Long"));
}
}
Non-Profit Order
Location: Null
Total Price: 0.0
I'm not sure if I'm calling the 'price' and location' wrong in my string, or if I'm doing something wrong in trying to implement those methods from the abstract Order class
Thanks for any and all help!

Your super constructor doesn't set the location
public Order(double price, String location){
}
so this constructor
public NonProfitOrder(double price, String location) {
super(price, location); // calls super class' constructor
}
doesn't actually set the price and location.
Change the constructor for Order to
public Order(double price, String location){
this.double = double;
this.location = location;
}
Un-initialized fields are given a default value. For reference types, that value is null. For numerical types, the value is 0. For boolean types, the value is false. That's what you were seeing.

You have just missing to assign your attributes in the abstract class.
public Order(double price, String location){
this.price = price;
this.location = location;
}

You have not initialized instance variables location and price.
So Java provides default values for those.
Here location is type String object so default value is null
The price is double type so default value is 0.0.
Those values are printing as output in your case.
So try to initialize them in Order class constructor
public Order(double price, String location){
this.double = double;
this.location = location;
}

Related

i can't get the right output in java

I have a problem with my program and I don't know why the names and the IDs of the objects don't show up right in the output and also the balance is not used in chkBalance() method Why ??I think the problem with the constructor but? ... and the output I get from this code is ...:
Customer Name Customer ID Balance
null 0.0 200
null 0.0 200
null 0.0 200
public class BankAccount {
private int Balance;
public String AccHolder_Name;
public double AccHolder_ID;
public BankAccount(String Name ,double ID,int Balance) {
Name = AccHolder_Name;
ID = AccHolder_ID;
}
public void withDraw(int a) {
Balance=a-Balance;
}
public void deposit(int b) {
Balance=b+Balance;
}
public int chkBalance(){
deposit(500);
withDraw(700);
return Balance;
}
public void Display () {
System.out.println(AccHolder_Name+"\t\t"+AccHolder_ID+"\t\t"+Balance);
}
public static void main (String args []) {
BankAccount o1=new BankAccount("Aos" , 1101558733 ,3000);
BankAccount o2=new BankAccount("Ahmed" , 1101978733,5000);
BankAccount o3=new BankAccount("Ali",1111650924,7000);
System.out.println("Customer Name\tCustomer ID\tBalance");
o1.chkBalance();
o2.chkBalance();
o3.chkBalance();
o1.Display();
o2.Display();
o3.Display();
}
}
In your constructor you are assigning null to the given parameters and never assign Balance
public BankAccount(String Name ,double ID,int Balance) {
Name = AccHolder_Name; // Will assign #AccHolder_Name to #Name
ID = AccHolder_ID;
}
So you should reverse this assignment and set the Balance field with the given parameter :
public BankAccount(String Name ,double ID,int Balance) {
AccHolder_Name = Name; // Will assign #Name to #AccHolder_Name
AccHolder_ID = ID;
this.Balance = Balance;
}
And about your variables names you should take a look to the naming convention.
The variables should use camel case and for good practice be well representative of their function.
So AccHolder_Name should be accHolderName for example.
Your assignments in the constructor is the wrong way arround. Also, you forgot to assign the Balance argument, which causes Balance to default to 0 and results in 200 after the calculations.
public BankAccount(String Name, double ID, int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
An important note on your naming conventions: variables in Java use camel case. It is also discouraged to abbreviate variable names unless they are considered an abbreviation standard. The resulting code would then be:
public BankAccount(String name, double id, int balance) {
this.accountHolderName = name;
this.accountHolderId = id;
this.balance = balance;
}
The constructor of the BankAccount is indeed wrong. Since what '=' operation does is to give the value of the right variable to the left variable, and your code is reversed.
Another problem is that you don't initialize your Balance in your constructor and the compiler will then simply initialize it to 0.
Constructor has issue. Copy bellow code and replace your constructor and check.
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
My suggestion is to learn java more. Basic you can learn from Java Tutorial.
In the constructor you are assigning it in the other way. Assign it as below
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name = Name;
this.AccHolder_ID = ID;
this.Balance = Balance;
}
There is always the variable you want to set on the left side and the value for it on the rigt side. As you want to set the String AccHolder_Name to the Name you are giving in the constructor, you have to do it just the other way around.
There are several mistakes:
a. Your constructor is incorrect and not saving the provided
variables.
this.AccHolder_Name=Name ;
this.AccHolder_ID=ID;
this.Balance=Balance;
b. Your withdraw method is incorrect. It should be (balance =
balance-a)
Please see the correct code below.
public class BankAccount {
private int Balance ;
public String AccHolder_Name;
public double AccHolder_ID;
public BankAccount(String Name ,double ID,int Balance) {
this.AccHolder_Name=Name ;
this.AccHolder_ID=ID;
this.Balance=Balance;
}
public void withDraw(int a) {
Balance=Balance-a;
}
public void deposit(int b) {
Balance=b+Balance;
}
public int chkBalance(){
deposit(500);
withDraw(700);
return Balance;
}
public void Display () {
System.out.println(AccHolder_Name+"\t\t"+AccHolder_ID+"\t\t"+Balance);
}
public static void main (String args []) {
BankAccount o1=new BankAccount("Aos" , 1101558733 ,3000);
BankAccount o2=new BankAccount("Ahmed" , 1101978733,5000);
BankAccount o3=new BankAccount("Ali",1111650924,7000);
System.out.println("Customer Name\tCustomer ID\tBalance");
o1.chkBalance();
o2.chkBalance();
o3.chkBalance();
o1.Display();
o2.Display();
o3.Display();
}
}

Undefined Constructor error

Am trying to implement a system for a car dealer, but when I try to instantiate my Car class in a derived class, I get the error message
Multiple markers at this line
- The constructor Car(String, int, String, String, double, double) is
undefined
Here's the parent class Car:
package Number3;
public class Car {
private String plateNum;
private int year;
private String make;
private String model;
protected double costPrice;
protected double sellingPrice;
public Car()
{
plateNum = "";
year = 1990;
make = "";
model = "";
costPrice = 0.0;
sellingPrice = 0.0;
}
public Car(String plateNum,int year,String make,String model,double costPrice,double sellingPrice)
{
this.plateNum = plateNum;
this.year = year;
this.make = make;
this.model = model;
this.costPrice = costPrice;
this.sellingPrice = sellingPrice;
}
public double getCostPrice()
{
return costPrice;
}
public double computeSellPrice()
{
sellingPrice = costPrice;
return sellingPrice;
}
public void displayCarDetails()
{
System.out.println("Plate number: "+plateNum);
System.out.println("Year: "+year);
System.out.println("Make: "+make);
System.out.println("Cost price: "+costPrice);
System.out.println("Selling price: "+sellingPrice);
}
}
and the subclass newCar:
package Number3;
public class newCar extends Car{
private double tax;
public newCar(String plateNum,int year, String make, double costPrice, double sellingPrice, double tax)
{
super(plateNum,year,make,costPrice,sellingPrice); //where the error is found
this.tax = (25/100);
}
public double computeSellPrice()
{
sellingPrice = costPrice + (costPrice * tax);
return sellingPrice;
}
public void displayCarDetails()
{
super.displayCarDetails();
}
}
Any help would be appreciated.
The signature of your Car constructor does not match the signature in the derived class.
In your Car class, this is the constructor:
public Car(String plateNum,int year,
String make,String model,double costPrice,double sellingPrice) {
...
}
It is String, int, String, String, double, double)
While in the derived class:
you have:
super(plateNum,year,make,costPrice,sellingPrice)
Which is int, int, String, double, double
Change the arguments in call to Super in your newCar class to match the constructor of your Car class. That is, in your newCar class, the line
super(plateNum,year,make,costPrice,sellingPrice)
should be :
super(plateNum, year,
make, model, costPrice, sellingPrice)
The Car class does not have a constructor that takes 5 parameters.
It is defined as
public Car(String plateNum,int year,String make,String model,double costPrice,double sellingPrice)
{
...
}
and you're trying to call it without passing the model parameter.
super(plateNum,year,make,costPrice,sellingPrice); //where the error is found
Your super/parent class Car has a no-argument constructor public Car() { and the following 6-parameter constructor which is being called from the sub/child class constructors using the keyword super.
public Car(String plateNum,int year,String make,String model,double costPrice,double sellingPrice)
Notice, that it expects String model as its fourth parameter but your public newCar() constructor is passing it only five parameters. The parameter model is missing.
public newCar(String plateNum,int year, String make, double costPrice, double sellingPrice, double tax)
{
super(plateNum,year,make,costPrice,sellingPrice); // model MISSING!
So, to fix it, either modify the constructor to accept model as well (just like in your usedCar() constructor) or pass null to the super class constructor as
super(plateNum,year,make,null,costPrice,sellingPrice); // model = null

Passing a Class type within a constructor of another class?

Do forgive me if the title is not correct, I thought this very question has to with "Polymorphism" but didn't want to complicate the title.
I am learning Java and following "Java: Learn to Program", As I am going along, I am applying the knowledge and creating my own scenarios to see
how "Polymorphism" is applied. I would appreciate it if someone can help me understand how to do this task. I have three classes:
Abstract Employee
Manager (Subclass of Employee)
Restaurant
Employee class and Manager class are pretty straight forward. I am trying to create a restaurant and every restaurant has a manager. My question is:
Should I pass "Manager" type as constructor arguments of "Restaurant" class or instantiate the "Manager" object in the constructor?
public abstract class Employee{
private String _empName;
private double _empSalary;
public Employee( string name, double salary){
_empName = name;
_empSalary = salary;
}
public void setEmpName( String name ){
_empName = name;
}
public String getEmpName(){
return _empName;
}
public void setEmpSalary( double salary ){
_empSalary = salary;
}
public double getEmpSalary(){
return _empSalary;
}
}//CLASS
public class Manager{
private double _yrsOfExp;
public Manager( String name, double salary, double experience ){
super(name, salary);
_yrsOfExp = experience;
}
public void setManagerExperience( double years ){
_yrsOfExp = years;
}
public double getManagerExperience(){
return _yrsOfExp;
}
}//CLASS
This is where I need help, I am declaring the constructor with "MANAGER TYPE". Should I be declaring the instance of "Manager" with the construction instead of
passing "Manager type" with the constructor, please?
public class Restaurant{
private Manager _manager;
private String _location;
//CONSTRUCTOR 1
//SHOULD I PURSUE IT THIS WAY OR
public Restaurant( Manager manager, String location){
_manager = manager;
_location = location;
}
//CONSTRUCTOR 2
//SHOULD I DO IT THIS WAY?
public Restaurant( String name, double salary, double experience, String location){
super(name, salary, experience);
_location = location;
}
public String toString(){
String str = "";
return str;
}
}//CLASS
This is partly a matter of taste and of what else you're going to do with the objects.
If you may ever want to refer to Managers independently, then they want to be their own object rather than properties of the Restaurant.
Since a Restaurant is not itself a Manager, I would suggest that it shouldn't take a Manager's properties in its constructor, and should instead have a Manager assigned to it (either in the constructor or in a setManager() call).
Among other things, that will make much more sense if one Manager is ever in charge of two Restaurants.

how would I use an if statment to change the value of an attribute?

I want to be able to give a specific value to discount depending on certain requirements like the following age: > 25 and profession = teacher / professor get 10% discount, age < 25 and gradepoint > 7 get 25% discount
this is my code so far I am using double OO paradigm:
public class customer {
//attribute definitions
private String name;
private String address;
private String profession;
private Integer age;
private Integer gradepoint;
private double discount;
//constructor
public customer(String newName, String newAddress, String newProfession, Integer newAge, Integer newGradepoint, double newDiscount)
{
setName(newName);
setAddress(newAddress);
setProfession(newProfession);
setAge(newAge);
setGradepoint(newGradepoint);
setDiscount (newDiscount);
}
//getters
public String getName()
{ return name;}
public String getAddress()
{ return address;}
public String getProfession()
{ return profession;}
public Integer getAge()
{ return age;}
public Integer getGradepoint()
{ return gradepoint;}
public double getDiscount()
{ return discount;}
//setters
public void setName (String newName)
{ name = newName;}
public void setAddress (String newAddress)
{ address = newAddress;}
public void setProfession (String newProfession)
{ profession = newProfession;}
public void setAge (Integer newAge)
{ age = newAge;}
public void setGradepoint (Integer newGradepoint)
{ gradepoint = newGradepoint;}
public void setDiscount (double newDiscount)
{ discount = newDiscount;}
//methods
}
Would I need to create a sub class called discount or each type of discount? or I can write a method directly into this customer class to control the discount?
write a method directly into this customer class to control the discount?
This. Make it a calculated field. Kill setDiscount function, kill discount variable, and make the getDiscount function into something like:
public double getDiscount() {
if (...) return ...;
if (....) return ...;
...
}
...unless you want to have this as the default discount, and still allow modification, in which case keep discount as a property, and move this whole logic into the constructor, having conditional setDiscount() calls.
Your getDiscount function would ideally do the calculation and return the appropriate discount for the current object. For example:
public double getDiscount()
{
if (getAge() < 25 && getGradepoint() > 7)
{
return .25;
}
else if // other logic...
}
Although not the simplest solution, I would abstract the discount calculation to a separate interface and class as well as having an override discount value in the customer object.
E.g.
public interface DiscountManager<T>
{
public double getDiscount(T discountObject);
}
public abstract class AbstractCustomerDiscountManager extends DiscountManager<Customer>
{
public double getDiscount(Customer customer)
{
if (customer.hasCustomDiscount()) { return customer.getDiscount(); }
else { return calculateDiscount(customer); }
}
public abstract double calculateDiscount(Customer customer);
}
public class DefaultDiscountManager extends AbstractCustomerDiscountManager
{
public double calculateDiscount(Customer customer)
{
double discount = 0;
if ((customer.getAge() != null) && (customer.getAge() < 25)) { discount += 25; }
...
return discount;
}
}
Probably over time different rules evolve. At the spot where the discounting takes place, in the order, the discount and and a reference to the rule applied should be stored together.
This kind of business logic could have its own class. A generic solution would even be to store the rule as scriptable code (BeanShell = Java, or JavaScript) and use java's scripting API. So that this kind of business logic resides more with the business managers, and the rules can be presented and edited.

Java Code for Inventory Program Part 3 will not compile

Made correction to previous errors, this error now comes up.
C:\Documents and Settings\AdminUser\My Documents\InventoryPart3.java:93: invalid method declaration; return type required
public Television(int ItemNumber, String ProductName, int UnitsStock, double UnitPrice, String mfgName) {
^
1 error
Tool completed with exit code 1
class Television { //class name and attributes
private String ItemNumber; //item # of product
private String ProductName; //product name
private double UnitsStock; //# of units in stock
private double UnitPrice; //Price per unit
private String SerialNumber; //serial number of product
private double InventoryValue; //The dollar value of the inventory in stock
//constructor
public Television (String item, String product, double units, double price, String serial) {
ItemNumber = item;
ProductName = product;
UnitsStock = units;
UnitPrice = price;
SerialNumber = serial;
} //end constructor
///getter and setter methods for Television
public void setItemNumber (String item) { //setter for item number
this.ItemNumber = item;
} //end setter item number
public String getItemNumber() { //getter for item number
return ItemNumber;
} //end getter item number
public void setProductName (String product) { //setter for product name
this.ProductName = product;
} //end setter product name
public String getProductName() { //getter for product name
return ProductName;
} //end getter product name
public void setUnitsStock (double units) { //setter for units in stock
this.UnitsStock = units;
} //end setter units in stock
public double getUnitsStock() { //getter for units in stock
return UnitsStock;
} //end getter units in stock
public void setUnitPrice (double price) { //setter for unit price
this.UnitPrice = price;
} //end setter unit price
public double getUnitPrice() { //getter for unit price
return UnitPrice;
} //end getter for unit price
public void setSerialNumber (String serial) { //setter for serial number
this.SerialNumber = serial;
}//end setter for serial number
public String getSerialNumber() { //getter for serial number
return SerialNumber;
}//end getter for serial number
//calculate individual product inventory value
public double getInventoryValue(){
return UnitsStock * UnitPrice;
}//end calculate individual product inventory value
//calculate total inventory value
public double calculateInventory(){
return UnitPrice * UnitsStock;
}//end calculate total inventory value
///end getter and setter methods for Laptop
} //end class Television
class Manufacturer extends Television {
private String manufacturerName;
//constructor
public Television(int ItemNumber, String ProductName, int UnitsStock, double UnitPrice, String mfgName) {
super(ItemNumber, ProductName, UnitsStock, UnitPrice, ManufacturerName);
this.manufacturerName = mfgName;
}//end constructor
//getter and setter for class Manufacturer
public void setmanufacturerName(String mfgName) {
this.manufacturerName = mfgName;
}
public String getmanufacturerName() {
return manufacturerName;
}
//end getter and setter for class Manufacturer
//calculate total inventory value
public double calculateInventory(){
return ((UnitPrice * UnitsStock));
}//end calculate total inventory value
//calculate restocking fee method
public double getcalculateRestockFee() {
return getInventoryValue();
}//end calculate restocking fee method
}//end class Manufacturer
So there are two errors. The first one occurs on line 93 of the file InventoryPart3.java. On that line you will find the code:
super(ItemNumber, ProductName, UnitsStock, UnitPrice);
Which is actually a call to the constructor of the television class. However, the constructor of the television class accepts 5 parameters: String, String, double, double, String but you are passing only 4.
The second error occurs on line 120 of the same file. In this case you seem to be calling a method but you left out the parenthesis. That is, the code should be:
getInventoryValue()
The constructor of television which you are trying to call from the manufacturer class using super does not exist in television class. Please see the parameters in the super() call and the actual parameters in the Television constructor. The getInventoryValue function is not there in the Television class.Hence it is throwing an error for the super.getInventory call
The first error is related to your Television constructor. Your Television constructor takes 5 arguments of type String, String, double, double, String. In your Manufacturer class, you're calling the superclass constructor with an int, string, int, and double. In a subclass, your super() constructor call must match one of the constructors in the base class (Television).
For the second error, your call to getInventoryValue has a syntax error. To call a method in Java, you have to put parentheses after the name of the method:
return super.getInventoryValue() * 0.10;
Note that in this case, the super. part is optional. The getInventoryMethod() exists in the super class, and is not private, so you can call it from the subclass like this:
return getInventoryValue() * 0.10;

Categories