This question already has answers here:
Why might one also use a blank constructor?
(10 answers)
Java entity - why do I need an empty constructor?
(8 answers)
Why Default constructor need to declare in POJO file which has Parameterized Constructor while instantiating Object?
(5 answers)
Default constructor does not initialize the instance members of the class?
(7 answers)
Closed 5 years ago.
Is it okay to use an empty constructor in Java? For example, when loading the data from a MySQL database, I want to do something like:
ResultSet set = statement.executeQuery();
while (set.next()) {
Faction faction = new Faction();
faction.setId(UUID.fromString(set.getString("id")));
faction.setName(set.getString("name"));
}
Because I already have a constructor for the faction class,
public Faction(Player player, UUID uuid) {}
I was wondering if I can have a plain constructor and just set the values as and when.
Otherwise I could create a constructor using parameters that match the mySQL data (public Faction(String name, UUID uuid, String announcement..etc), to load in.. Not sure what is best practice?
If the object state should not change when the Faction class is instantiated, provide a constructor with args and removing setter is better.
In this way, you avoid undesirable behavior.
Now, according to your saying, you probably need to set many String parameters.
Doing it with a constructor is very error prone as you may do a mistake in the parameter order when you use it.
To achieve your need, you have two main ways :
using an empty constructor and then setters as you propose (desirable if the object is mutable)
if your object is immutable, you could use the Builder pattern to construct an immutable object (You write something like : Faction faction = new Faction.Builder().name(name).uuid(uuid).announcement(announcement).build();
It depends on your use case. If you dont want the class variables to change once you set them then in that case declare those variables as final and use the parametised constructor. If you want the variables to change once you set them, then use the default constructor with setters and getters.Both the options are perfectly fine.
Related
This question already has answers here:
Methods vs Constructors in Java
(11 answers)
Closed 2 years ago.
actually i'm beginner my questions might be silly And my doubt is what was actual purpose of methods vs constructors in java,
we can pass values in both methods & constructor parameters,
which one is recommended and why??
A Java method is use to perform some action which is also know as Function. Where you can pass parameter. They must have return type.
A Constructor is special method use to initialise the object . Constructor must not have return type. Constuctor name must be same as class name.
Constructor is used to initialize an object whereas method is used to exhibits functionality of an object.
Constructors are invoked implicitly whereas methods are invoked explicitly.
Constructor does not return any value where the method may/may not return a value.
In case constructor is not present, a default constructor is provided by java compiler. In the case of a method, no default method is provided.
Constructor should be of the same name as that of class. Method name should not be of the same name as that of class.
This question already has answers here:
what is the use of a parameterized constructor in java?
(7 answers)
Purpose of a constructor in Java?
(12 answers)
Closed 4 years ago.
Just why are they used? I'm a beginner by the way. I understand default constructors that initialize values because it makes logical sense, but why use a constructor with parameter to say that an instance variable age for example is equal to a. What is the purpose? What happens without it and only the initializer constructor? Other questions asked on here do not make sense tome
For example:
public class MyCats {
private int age;
private String name;
public MyCats(int a, String n) { // why do I need this?
age = a;
name = n;
}
public MyCats() {
age = 0;
name = "";
}
}
That's for easily creating your class without needing extra code. For example, instead of doing:
MyCats a = new MyCats();
a.setAge(12);
a.setName("Foo");
You can just do:
MyCats a = new MyCats(12, "Foo");
Simpler, hum?
Other reasons you might prefer the later, if shortness is not enough:
You can initialize all calculated fields that depend on several fields inside the constructor, using the values provided.
You can validate input and thrown exceptions in case of invalid arguments, even for checks that requires multiple arguments for that.
You must do that if your fields are final and your class immutable, in which case there is no setters available.
Mostly in the last case, it's very useful to be able to check for correctness upon construction and disallow any objects from being in a invalid state, saving lots of errors later on.
This question already has answers here:
Why do we need a default no argument constructor in Java?
(7 answers)
Closed 5 years ago.
Why would anyone want to define a zero argument constructor when a default parameterless constructor is created during compile time anyway? Are there any benefits to doing so? are there any cases where it is better to define a zero argument constructor within a class for the sole purpose of preventing the default from being created during compile time?
Simple: you define it when you need it.
For example to call another constructor with some default values which are then used by the other constructor to initialize fields of the class.
When you write down an "empty" constructor that does nothing besides calling the super constructor then sure - you wrote useless code that should go away.
A default constructor is added by java internally if user does not define any parametrised constructor. It initialises any uninitialised fields to their default values.
Like int to 0
string to null
object to null
It's needed if you want to execute an init-function as soon as a new object of the class is created. For Example:
public class Example {
public Example() {
init();
}
public void init() {
//do some Stuff
}
}
But Just defining it without doing anything is not sensefull.
This question already has answers here:
In Java, why do people prepend fields with `this`?
(16 answers)
Closed 8 years ago.
I am looking at a very old code-base, and every field access follows this pattern:
void method() {
TYPE fieldRef = this.field;
// Use fieldRef instead of field
}
I can't figure out why this pattern is followed rigorously. Is there some performance benefit to this? Does it have something to do with how fields behave with inheritance?
this always refers the current class variables in the scenario you mentioned
so the benefit is just that the purpose of assigning value is satisfied the way it should be
Is there some performance benefit to this?
No its not for performance improvement
Does it have something to do with how fields behave with inheritance?
only if your parent class variables have same names Yes, or it does not have any thing to do with Inheritance as well
EDIT:
// Use fieldRef instead of field
this we usually do because in java if your field is an Object, it maintains reference and any modifications we do gets reflected in original object property.
Maybe the coder wants to catch the instance object that this.field refers to with a temporary reference and immediately assign a different instance object to this.field.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Use string in place of variable name
Is there any way in Java that allows an object to be created using a string?
Let's say, i have a class called "Toyata", is there anyway i can create an object of Toyata
using the string variable s in class Car?
public class Car{
String s = "Toyota";
}
public class Toyota{
int speed;
public Toyota(int speed){
this.speed=speed;
}
}
You can use reflection, but you need a fully qualified classname:
https://stackoverflow.com/a/4030634/1217408
EDIT:
Hovercraft Full Of Eels's comment about using a map lookup is probably far more appropriate in this situation.
You need to query for class (assuming it's in the default package this should work) via the value of s. Then you have to lookup the proper constructor via your class' getConstructor() method. Since Toyota does not contain a default constructor, you need to query for one that matches your expected parameters. In this case, it's an int. int is represented in Class form by Integer.TYPE. Finally after that is all said and done, you can call newInstance() on the constructor with the desired speed passed in and you should have a new instance ready to use. Of course there will be a few checked exceptions to handle.
Class<?> clazz = Class.forName(s);
Constructor constructor = clazz.getConstructor(new Class[] {Integer.TYPE});
Toyota toyota = (Toyota) constructor.newInstance(new Object[] {90});