简体   繁体   中英

Constructors with the same primitive type as parameter

I have an assignment that asks me to create a Data Class as a "Node Center" for all my other classes, such as a class for LinkedList, Stack, & Queue to "feed" on. I'm creating constructors in the Data class to work on the LinkedList, Stack, & Queue classes. I wasn't having any problems until I implemented my constructor for my Queue. In my Stack portion of the Data class, I had already created a public Data constructor with an int as my parameter in the constructor. When I try to create another public Data constructor with an int as my parameter for the Queue, I get the error: Data(int) is already defined in Data. Here is my Stack code:

/*
    STACK WITH AN ARRAY
    */
    int size; //initialize size
    int stackArray[]; //initialize array
    int top; //initialize top

    public Data(int size) //constructor
    {
        this.size = size;
        this.stackArray = new int[size];
        this.top = -1;
    }

And here is my Queue code:

/*
    QUEUE WITH AN ARRAY
    */
    public int Queue[]; //establish queue array and variables
    public int front;
    public  int rear;
    public int queueSize;
    public int len;

    public Data(int nQueue)//constructor
    {
        size =nQueue;
        len = 0;
        Queue = new int[size];
        front = -1;
        rear = -1;
    }

How do I fix this so I can have 2 constructors with the same parameter type?

They are both constructors of type int. Java doesn't care about what you name the int argument, so they look like the same constructor (at least to java). Since you cannot have two constructors with the same arguments, you have two options.

  1. Give one of the constructors a different data type argument.
  2. Give one of the constructors another argument. (2 arguments)

Either of these will allow the jvm to tell the difference between your two constructors.

It's not possible to have same name and same signature for two methods or constructors.

In your case if you call new Data(10) to create an instance of Data the compiler won't know which constructor to call to create the instance.

You can have a second boolean argument to mention what kind of instance to be created.

public Data(int size, boolean isQueue)//constructor
{
  if(isQueue){
    len = 0;
    Queue = new int[size];
    front = -1;
    rear = -1;
  }else{
    this.size = size;
    this.stackArray = new int[size];
    this.top = -1;
  }
}

JLS: §8.4.2 Method Signature

You cannot create two constructor having same number of parameters in the list and their types. What you can do is create sub classes for Queue and Stack and define constructor for each of them in respective sub classes.

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