Bibin Mathew
Bibin Mathew

Reputation: 213

Array as constructor parameter

I Have a problem . I am learning java and this sample code is not working, saying :

 $javac Quicksort.java 2>&1
    Quicksort.java:16: error: constructor Quicksort in class Quicksort cannot be applied to given types;
    Quicksort qc = new Quicksort(values);
    ^
    required: no arguments
    found: int[]
    reason: actual and formal argument lists differ in length
    1 error

Not able to figure out why . Can anyone help ??

My code snippet is :

   public class Quicksort{
   public int[] number ;

   public void Quicksort(int[] values){
       this.number=values;
   }
   public void print(){
       for (int i=0; i<number.length;i++)
           System.out.println(number[i]);



   }
   public static void main(String[] args){
       int[] values = {3,4,5,6,7,8};
       Quicksort qc = new Quicksort(values);
       qc.print();
   }

}

Upvotes: 3

Views: 1426

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 122026

Your definition of Constructor is incorrect.

 public void Quicksort(int[] values){
       this.number=values;
   }

Should be

 public  Quicksort(int[] values){
       this.number=values;
   }

constructor wont have a return type.

Providing Constructors for Your Classes

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.

For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
    gear = startGear;
    cadence = startCadence;
    speed = startSpeed;
}

Upvotes: 11

sanbhat
sanbhat

Reputation: 17622

public void Quicksort(int[] values){
       this.number=values;
 }

should be

public Quicksort(int[] values){
       this.number=values;
}

Your constructor should not have a return type (in your case void). Otherwise it will be considered as a method

Upvotes: 4

Related Questions