+ 2
Is constructer essential in java programming
11 Respuestas
+ 8
Then we will use functions but we will get a drawback of not to keep function name same as class name
+ 7
Yes
+ 7
Hmm... bt then you need to define the return data type and also static or instance//only for function
+ 5
you need to understand and know how/when to use them but it is not necessary to have a constructor for every class.
+ 3
what will be without constructer?? There are other option to initialize the objects.
+ 3
how it's a drawback??
+ 3
Yes it's essential.
It's the most optimal and easiest way of initializing attributes when an object is created.
Take the Scanner for example.
Scanner sc = new Scanner(System.in);
System.in is the inputstream being passed to the Scanner class's constructor.
If constructors were never a thing, it may be like this:
Scanner sc = new Scanner;
sc.next(); // ERROR
sc.inputStream = System.in;
sc.next(); // OK
Now if I want to read a file:
Scanner sc = new Scanner(File);
Compared to:
Scanner sc = new Scanner;
sc.file = File;
Now if I did:
sc.InputStream = System.in;
This line would likely cause huge issues.
So, one benefit in this case is that it forces some attributes to be completely hidden from the programmer, as they may cause problems if both are used together.
+ 2
If yes then what if not
+ 2
I know that but we can use different name for the same.
+ 2
let's leave it and thanx for discussion
0
constructtor is necessary because....it initialize the object with default values