+ 1
Void constructors in java
I tried to define a constructor as “public void”, so it results nothing. But if i write only public,it results. Why is this like that?
5 Respostas
+ 2
when you include void the only valid construct in this case is a method declaration, so you have a method with the signature "telephone ()" which isn't the same as the class "telephone". Since you don't invoke the method, nothing happens.
In the other case you have declared a constructor, and any code will execute on object creation. This is the reason for the difference
+ 2
class telephone{
public void telephone(){
System.out. println(“hello world”);
}
}
public class nokia{
public static void main(String[] args) {
telephone obj=new telephone();
}
}
if i write like this,nothing is shown. but if i only write “public telephone” so it writes “hello world”.
i wonder why the reason is . And i know constructors dont have return type. so why it is not allowing “void” there?
thanks for all the answers.
+ 1
Please post a code demonstrating what you mean
+ 1
Constructors don't have a return type. By nature, a constructor must be void, and thus you don't include a return type when you're defining it
+ 1
It's just proper syntax to have "public telephone()" without void. I'm honestly surprised you're not getting a syntax error (: