0

How do we check if a variable is passed into a constructor in JAVA ?

What I need to do is if a String attribute isn't passed to the constructor, then this String attribute is set to "null"

13th Aug 2020, 5:16 PM
Adrien Linares
Adrien Linares - avatar
5 ответов
+ 3
You need to overload the constructor. Create one constructor that takes in all the parameters that you need and another that omits the String parameter that you want to be null. You can then call the 1st constructor from the 2nd constructor passing the String as null. MyObj(...parameters) { // constructor without String MyObj(...parameters, null); // call 2nd constructor with String value as null } MyObj(...parameters, String str) { if(str == null) { .... } }
13th Aug 2020, 5:48 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
if ( String_variable == null ) { ... } But its all depends on how you implement it.. You need to implement constructor to set its values.. If you don't want to set, implement a default constructor without arguments. That sets to default values....
13th Aug 2020, 5:22 PM
Jayakrishna 🇮🇳
+ 1
write two constructors one with argument and second without argument. Then constructor can call another constructor by using this()
13th Aug 2020, 5:48 PM
zemiak
0
Mmm yeah The problem is that when I don't pass one of the argument of the constructor in the main class, i get an error
13th Aug 2020, 5:33 PM
Adrien Linares
Adrien Linares - avatar
0
Adrien Linares there shloud match the number of constructor arguments you are using with the constructors you defined. So write overloading of constructor or send default or null value.. Ways to overload... Ex: class1(int i) {...} cpass1(int iI, int j) {this(i);. } class1(int i, int j, int k) { this(i, j);...}
13th Aug 2020, 6:51 PM
Jayakrishna 🇮🇳