Search code examples
javaabstract-classextend

Extend and print from an abstract class


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!


Solution

  • 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.