package mainData;
public class Hello{
public void Hello(String sData, int ... nAges){
for(int x : nAges){
System.out.println(sData + " " + x);
}
}
public static void main(String args[]){
Hello ages = new Hello("Age: ", 5, 6, 7, 8);
}
}
When i change the constructor (Hello > Hello2) this code running without problem. But why this code not working?
You are defining a method called Hello
of return type void
. A constructor does not have a return type; use the following instead:
public Hello(String sData, int ... nAges) {
for (int x : nAges) {
System.out.println(sData + " " + x);
}
}
Remove void
from your constructor, and it should work . If you give a return type , then you are creating a method, not a constructor.
I suspect that your code doesn't run without a problem when you rename Hello
to Hello2
. It may compile and execute, but it won't print out the nAges
arguments. Note that compilation isn't a sufficient test of correctness.
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.