简体   繁体   中英

In Java, how to invoke a constructor with different variable types?

I guess it's a simple question, but I've just started to learn! :P

I need to invoke the ParkingTicket(parker, parkee) constructor in the checkParking() gateway method (if the "if" statement is true) but I'm getting the following error: incompatible types: int cannot be converted to Car

public class ParkingTicket
{
  private static int count = 1000;
  private final String referenceNumber;
  private final String carLicensePlate;
  private int carMinutesParked;
  private int meterMinutesPaid;
  private static final String prefix = "V";

  private ParkingTicket(String recordedLicense, int carParkedMinutes, int meterPaidMinutes)
  {
      count = (count + 1);
      referenceNumber = prefix + count;
      carLicensePlate = recordedLicense;
      carMinutesParked = carParkedMinutes;
      meterMinutesPaid = meterPaidMinutes;
  }

  private ParkingTicket(Car parker, ParkingMeter parkee)
  {
      this(parker.getLicensePlate(),
           parker.getMinutesParked(),
           parkee.getMinutesPaid());
  }

  public static int checkParking(Car minutesParked, ParkingMeter minutesPaid)
  {
    if (minutesParked.getMinutesParked() > minutesPaid.getMinutesPaid())
    {
       new ParkingTicket(minutesParked.getMinutesParked(), minutesPaid.getMinutesPaid());       
    }
    else
    {
       ParkingTicket pt1 = null;
    }
  }
} 

Thanks in advance for all the help!

On the line

new ParkingTicket(minutesParked.getMinutesParked(), minutesPaid.getMinutesPaid());

You are trying to use the constructor

 private ParkingTicket(Car parker, ParkingMeter parkee)

As you can see this takes two arguments, a Car and and ParkingMeter

The arguments you are passing in are int

I'm guessing you want to call the first constructor? You just need to change the line to include the license

 new ParkingTicket(minutesParked.getLicensePlate(), minutesParked.getMinutesParked(), minutesPaid.getMinutesPaid());       

You should use pass the parameters that your constructor is expecting :

ParkingTicket ticket = new ParkingTicket(minutesParked, minutesPaid); 

I'd change the names of those variables though. minutesParked is not a good name for a Car and minutesPaid is not a good name for a ParkingMeter .

PS you probably want to do something with the instance you created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM