Abstract parent with Inheritance

Hi everyone!

Iv just finished two out of 3 sections of the Java course, and i feel allot more confidence with programming and general knowledge in Java.

However im facing a basic problem i tought someone could help me out with.

Im defining a abstract class with abstract methods (Veichle) with few sub-classes that extend the Abstract class and have overriten the methods. Now in the Abstract class we have for e.g:
Public Abstract String veichleType();
Public Abstract Boolean isTaxable();

Now what im doing is setting the child classes with those values.

My problem

however im trying to create a calculation class where the magic should happen. In my case i would like a class that a instance of veichle i belive?..
with a method to take in the Vehicletype, define if its an instance of the vehicle, and see what the inner value of the String type is and Boolean taxable is, if they are for e.g “Car and true”
then we have this method ( return type double) return a positive double value, and if its “ambulance false” return less ammount positive double value.

This comes in hand with the upcasting and downcasting and overwritting the object class?
But I have no clue on how that is achiveable. Any ideas?

To be clear, you have something like this:

public abstract class Vehicle {
  public abstract String vehicleType();
  public abstract boolean isTaxable();
}

public class Car extends Vehicle {
  @Override public String vehicleType() { ... }
  @Override public boolean isTaxable() { ... }
}

public class Ambulance extends Vehicle {
  @Override public String vehicleType() { ... }
  @Override public boolean isTaxable() { ... }
}

But you have given no details about how exactly this calculation takes place. Is the calculation based on the vehicleType() or isTaxable() or both?

Here is one way that you could have some calculation that is simply based on if it is taxable or not:

public class GasCostCalculator {
  private static final double TOTAL = 10.5;
  private static final double TOTAL_WITH_TAX = TOTAL * 1.05;

  public double chargeForGas(Vehicle vehicle) {
    if (vehicle.isTaxable()) {
      return TOTAL_WITH_TAX;
    }
    return TOTAL;
  }

If you gave more specifics about this “calculation” you are trying to do, I could give more help.

Thanks for responding @jmrunkle , I kind of figured some steps out very clear so let me paste in what iv done and how i meant with “calculate”

public abstract class Veichle {
    private String type;
    private Boolean taxClas;

    public Veichle(String type, Boolean taxClas) {
        this.type = type;
        this.taxClas = taxClas;
    }
    public Veichle(){

    }
    public abstract String getType();
    public abstract Boolean getTaxClas();


    @Override
    public String toString() {
        return "Veichle{" +
                "type='" + type + '\'' +
                ", taxClas=" + taxClas +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Veichle veichle = (Veichle) o;
        return type.equals(veichle.type) && taxClas.equals(veichle.taxClas);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, taxClas);
    }
}
public class Ambulance extends Veichle {

    public Ambulance(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Ambulance() {

    }

    @Override
    public String getType() {
        return "Ambulance";
    }

    @Override
    public Boolean getTaxClas() {
        return false;
    }
}
public class Motorcycle extends Veichle {

    public Motorcycle(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Motorcycle() {
    }

    @Override
    public String getType() {
        return "Motorcycle";
    }

    @Override
    public Boolean getTaxClas() {
        return true;
    }
}
    public Car(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Car() {

    }

    @Override
    public String getType() {
        return "Car";
    }

    @Override
    public Boolean getTaxClas() {
        return true;
    }

}

Now based on the super class and the inheritors, the only thing for now is that i wanted to know if they really are a “instanceof” veichle, and based on which type of veichle could determine how the tax could be calculated by using “if they are taxable”

So the calculator looks like this atm:

    public void veichleType(Veichle veichle) {
        Boolean tax;
        try {
            if (!(veichle instanceof Car || veichle instanceof Ambulance)) {

            }
        }catch (Exception e) {
            System.out.println("Not a valid Veichle");
        }
            tax = veichle.getTaxClas();
            var price = calculatePrice(tax);
            printMethod(price);
    }

    private void printMethod(double price) {
        NumberFormat.getCurrencyInstance().format(price);
        System.out.println("Fee is: ");
        System.out.println(NumberFormat.getCurrencyInstance().format(price));
    }

    private double calculatePrice(boolean tax) {
        LocalTime today = LocalTime.now();
        String timeString = today.format(formatter);
        var newTime = Double.parseDouble(timeString);
        System.out.println("Local time passed the taxometer is: ");
        System.out.println(newTime);
        System.out.println("----------");

        if (tax == true) {
            var cost = compareTime(newTime);
            return cost;
        }
        return 0;
    }

    private double compareTime(double hour) {
        if (hour >= 24.00 && hour <= 06.00) return 20.00;
        else if (hour > 06.00 && hour <= 12.00) return 30.00;
        else if (hour > 12.00 && hour <= 18.00) return 40.00;
        else if (hour > 18.00) return 30.00;
        return 0;
    }
}

My two guestions:

  1. My original guestion should have been: Is there a way to define following part:
  if (!(veichle instanceof Car || veichle instanceof Ambulance)) 
  • Without actually having to write all type of instances, I may have 100 classes that extend a car for e.g, there has to be a better way right?, and this was my original guestion that somehow ended up with the word calculation, so sorry for that haha!
  1. overal is this a correct solution? any better ideas? :slight_smile:
package org.example;

public class Car extends Veichle {

    public Car(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Car() {

    }

    @Override
    public String getType() {
        return "Car";
    }

    @Override
    public Boolean getTaxClas() {
        return true;
    }

}

package org.example;

public class Motorcycle extends Veichle{
    public Motorcycle(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Motorcycle() {
    }

    @Override
    public String getType() {
        return "Motorcycle";
    }

    @Override
    public Boolean getTaxClas() {
        return true;
    }
}

package org.example;

public class Ambulance extends Veichle{

    public Ambulance(String type, Boolean taxClas) {
        super(type, taxClas);
    }

    public Ambulance() {

    }

    @Override
    public String getType() {
        return "Ambulance";
    }

    @Override
    public Boolean getTaxClas() {
        return false;
    }
}

package org.example;

import java.util.Objects;

public abstract class Veichle {
    private String type;
    private Boolean taxClas;

    public Veichle(String type, Boolean taxClas) {
        this.type = type;
        this.taxClas = taxClas;
    }
    public Veichle(){

    }
    public abstract String getType();
    public abstract Boolean getTaxClas();


    @Override
    public String toString() {
        return "Veichle{" +
                "type='" + type + '\'' +
                ", taxClas=" + taxClas +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Veichle veichle = (Veichle) o;
        return type.equals(veichle.type) && taxClas.equals(veichle.taxClas);
    }

    @Override
    public int hashCode() {
        return Objects.hash(type, taxClas);
    }
}

Thanks for replying and taking your time, above is the current classes iv done.
Now when it comes to the calculation class im sorry i was a bit of topic and didnt really explain it that well. Take a look a current calculation iv done.

package org.example;

import java.text.NumberFormat;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TaxCalculator {
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH.mm");

    public void veichleType(Veichle veichle) {
        Boolean tax;
        try {
            if (!(veichle instanceof Car || veichle instanceof Ambulance)) {

            }
        }catch (Exception e) {
            System.out.println("Not a valid Veichle");
        }
            tax = veichle.getTaxClas();
            var price = calculatePrice(tax);
            printMethod(price);
    }

    private void printMethod(double price) {
        NumberFormat.getCurrencyInstance().format(price);
        System.out.println("Fee is: ");
        System.out.println(NumberFormat.getCurrencyInstance().format(price));
    }

    private double calculatePrice(boolean tax) {
        LocalTime today = LocalTime.now();
        String timeString = today.format(formatter);
        var newTime = Double.parseDouble(timeString);
        System.out.println("Local time passed the taxometer is: ");
        System.out.println(newTime);
        System.out.println("----------");

        if (tax == true) {
            var cost = compareTime(newTime);
            return cost;
        }
        return 0;
    }

    private double compareTime(double hour) {
        if (hour >= 24.00 && hour <= 06.00) return 20.00;
        else if (hour > 06.00 && hour <= 12.00) return 30.00;
        else if (hour > 12.00 && hour <= 18.00) return 40.00;
        else if (hour > 18.00) return 30.00;
        return 0;
    }
}

Main

package org.example;

public class Main {
    public static void main(String[] args) {
        var carObject = new Car("Car", true);
        TaxCalculator calc = new TaxCalculator();
        var motorCycleObject = new Motorcycle("Motorcycle", true);
        calc.veichleType(motorCycleObject);
        calc.veichleType(carObject);


        //var ambulanceObject = new Ambulance("Ambulance", false);
        //calc.veichleType(ambulanceObject);
        //calc.veichleType(ambulanceObject);
    }

}

So all im trying to see if the childclass is taxable then use a method to return current time with a value. I think i figured the calculation part, i mean its working? I guess its not really the best library to compare time… in the longer run for more complex calculations, so any ideas on what library to use would be appricated :slight_smile:

My org guestion: On the Calculation class I need to know if the instance really are a child right?
But the way its implemented is wrong…

  1. Im currently not doing anything if its not a Veichle?
    -How could this method be improved?
  2. What if i want to check 10 - 20 types of Veichles, i dont feel im gonna do if statement that is 20 lines long cheecking every instanceof right?

Overall thanks for the help!

Image: