user2650277
user2650277

Reputation: 6729

Constructor not working java

I get an error if i try to put the parameters at the following line

Sum s1 = new Sum(1,5,6);

Why do i get this error when there is a constructor called Sum with 3 parameters

package test;

class Sum {
    double num1,num2,num3;
    double[] result = new double[4];
   double[] Sum(int num1,int num2, int num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3; 
        result[0] = num1;
        result[1] = num2;
        result[2] = num3;
        result[4] = num1+ num2 + num3;
        return result;
    } 
}

public class Test {
    public static void main(String[] args) {
        Sum s1 = new Sum(1,5,6);
    }

}

Upvotes: 0

Views: 1688

Answers (5)

Ivan
Ivan

Reputation: 3062

You should create constructor that takes 3 int parameters, like this:

...
private int num1, num2, num3;

public Sum(int a, int b, int c) {
    this.num1 = a;
    this.num2 = b;
    this.num3 = c;
}

Upvotes: 0

Abhijeet Kale
Abhijeet Kale

Reputation: 1716

constructor does not return any value.

A constructor does not support any return type. Not even void.

The implicit return type by default is the class type in which it is declared.

Upvotes: 0

Eran
Eran

Reputation: 393771

This is wrong (an array of length 4 has indices from 0 to 3) :

result[4] = num1+ num2 + num3;

Change to

result[3] = num1+ num2 + num3;

Beside that, a constructor shouldn't have a return value.

Change

double[] Sum(int num1,int num2, int num3)

to

Sum(int num1,int num2, int num3)

and remove the return statement.

To summarize, the constructor should look like this :

Sum(int num1,int num2, int num3) {
    this.num1 = num1;
    this.num2 = num2;
    this.num3 = num3; 
    result[0] = num1;
    result[1] = num2;
    result[2] = num3;
    result[3] = num1+ num2 + num3;
} 

Upvotes: 1

nafas
nafas

Reputation: 5423

double[] Sum(int num1,int num2, int num3) 

is not constructor

you want to have this instead:

public Sum(int num1,int num2, int num3) 

here is an example of a contructor:

http://www.homeandlearn.co.uk/java/class_constructor.html

Upvotes: 4

Rahul Yadav
Rahul Yadav

Reputation: 1513

Your constructor has return type, Constructor do not have return statements. You need to change

public Sum(int num1,int num2, int num3) {
        this.num1 = num1;
        this.num2 = num2;
        this.num3 = num3; 
        result[0] = num1;
        result[1] = num2;
        result[2] = num3;
        result[3] = num1+ num2 + num3;
    } 

Upvotes: 3

Related Questions