-3

Why is the default constructor used in this method?

public static TicketCounterSingle getInstance() {
    if (instance == null) {
        instance = new TicketCounterSingle();
    }
    return instance;
}

This is the full class:

public class TicketCounterSingle {
    private static TicketCounterSingle instance;

    String Name;
    int avail;

    private TicketCounterSingle(String Name, int avail) {
        this.avail = avail;
        this.Name = Name;
    }

    public String getName() {
        return Name;
    }

    public synchronized boolean bookTicket(int ticket) {
        if (avail >= ticket) {
            avail = avail - ticket;
            return true;
        } else {
            return false;
        }
    }

    public static TicketCounterSingle getInstance() {
        if (instance == null) {
            instance = new TicketCounterSingle();
        }
        return instance;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Nisha
  • 1
  • Maybe there is just a default constructor? Could you show us the entire class **and** explain in detail what you cannot understand, please? Thanks... – deHaar Nov 06 '19 at 13:24

1 Answers1

0

Your code will not compile, because there is no default constructor.

TicketCounterSingle() {}

in your class.

There is a parameterized one:

private TicketCounterSingle(String Name, int avail) {
    this.avail = avail;
    this.Name = Name;
}

That means the default constructor will not be provided automatically, and you either have to provide a default constructor or call the parameterized one in a parameterized getInstance(String name, int avail) method:

public static TicketCounterSingle getInstance(String name, int avail) {
    if (instance == null) {
        instance = new TicketCounterSingle(String name, int avail);
    }
    return instance;
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
deHaar
  • 17,687
  • 10
  • 38
  • 51