-1

My code is:

public class Q2Client {
   public static void main(String[] args) {
   Q2 newq2 = new Q2(5);
   }
} 


class Q2 {
   int x;
   public void Q2 (int y) {
   int x = y;
   }
}

I get an error about not accepting an integer (required: no arguments) when creating the newq2, but the Q2 clearly takes an integer. When I remove the void in the Q2 class, it does not give me the error and runs fine. What about the void causes the parameter (int y) to be invalid?

FMG
  • 1
  • 5
    You're trying to use a method as a constructor. Remove the word `void` from `Q2`'s signature. Also you are creating a local variable `x` that is shadowing the class variable `x` – GBlodgett Dec 12 '19 at 00:51
  • just skip void in `public void Q2 (int y)` and you've meade the method a constructor which can be called by `new Q2(5)`. Right now Q2 has only the default constructor, which has no arguments, therefore the issue. – Curiosa Globunznik Dec 12 '19 at 00:52
  • In java, if you create a method that has the same name as the class, it's a "Constructor" instead of a regular method. It creates a new instance of the Q2 class, and automatically returns it (so you don't get to pick the return type.) – Andrew Rueckert Dec 12 '19 at 00:54

2 Answers2

-1

Constructors have no return type! Change your Q2 class as follows

class Q2 {
   int x;
   public Q2 (int y) {
     this.x = y;
   }
}
Khairyi S
  • 306
  • 2
  • 10
-2

coding like this:

 class Q2 {
     int x;
     public Q2 (int y) { // attention:remove the void 
     int x = y;
   }
}

means the method of Q2 is the constructor of class Q2,and it accept an param whose type is integer. BUT, if you define the method like this :

 public void Q2 (int y) { // attention:NOT remove the void 
      int x = y;
    }

means you tell the machine want to define an common method,ATTENTION: the class has none constructor! refer to JAVA Reference ,the default constructor,which has no param will be invoked, then you call new Q2(5) will be wrong.

Kevin
  • 160
  • 2
  • 3