Question

public class This_testing {

    int x,y;

    public This_testing(int x,int y){  //Why modifier void here would cause exception?
        this.x=x;
        this.y=y;
    }

    public static void main(String [] args){
        This_testing t =new This_testing(40,50);
        System.out.println(t.x+" "+t.y);
    }
}

Why using the modifier void for the constructor This_testing would cause the following exception :

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - 
constructor This_testing in class practice.This_testing cannot be applied to given types;
  required: no arguments
  found: int,int
  reason: actual and formal argument lists differ in length
    at practice.This_testing.main(This_testing.java:13)
Was it helpful?

Solution

Constructors don't return anything, not even void. It's simply how they're defined in the language spec.

You could make a method called This_testing that returns void but this would be considered a method, not a constructor (and as such, using new This_testing(x, y) would not compile).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top