+ 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?

11th Jul 2018, 5:20 PM
Murat Artan
Murat Artan - avatar
5 Antworten
+ 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
11th Jul 2018, 8:05 PM
Dan Walker
Dan Walker - avatar
+ 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.
11th Jul 2018, 7:43 PM
Murat Artan
Murat Artan - avatar
+ 1
Please post a code demonstrating what you mean
11th Jul 2018, 5:40 PM
Dlite
Dlite - avatar
+ 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
11th Jul 2018, 5:45 PM
Keto Z
Keto Z - avatar
+ 1
It's just proper syntax to have "public telephone()" without void. I'm honestly surprised you're not getting a syntax error (:
11th Jul 2018, 7:44 PM
Keto Z
Keto Z - avatar