Reputation: 87
I am new to java Can any one explain in below code we do constructor without parametre why?
java
import java.util.*;
public abstract class compte {
protected int numero;
protected String nom;
protected double solde;
protected String datecreate;
ArrayList<operation> op= new ArrayList<operation>();
public compte(int numero,String nom,double solde,String datecreate){
this.numero=numero;
this.nom=nom;
this.solde=solde;
this.datecreate=datecreate;
}
public compte(){
}
Upvotes: 0
Views: 91
Reputation:
If you don't have that constructor there, this statement won't compile[*]:
compte c = new compte();
An empty argument constructor is presumed if no constructors are defined. But you have to define one explicitly if there is another overloaded constructor defined by the class.
[*]: I suggest you to follow Java naming conventions. My example shows class name as compte
(to demonstrate using your code). It will be Compte
(with a capital c) in a code that follows convention.
Upvotes: 2
Reputation: 96385
Reasons to add a zero-arg constructor:
Because you want subclasses of this class to be able to be constructed using the zero-arg constructor. (If you create a constructor then the Java compiler won't create the no-arg one for you.)
Because you're using the class with a library like Hibernate that relies on the things it works with having a zero-arg constructor (it needs to instantiate objects with their own life-cycle without having to worry about constructor arguments).
Upvotes: 3
Reputation: 552
If you want to create a default object. However java will always initiate your variable with default values such as null, 0 for integer etc. But maybe you want your default empty object to have some other default values. For instace, in your case:
public abstract class compte {
protected int numero;
protected String nom;
protected double solde;
protected String datecreate;
ArrayList<operation> op = new ArrayList<operation>();
public compte(int numero, String nom, double solde, String datecreate) {
this.numero = numero;
this.nom = nom;
this.solde = solde;
this.datecreate = datecreate;
}
public compte() {
this.numero = 1;
this.nom = "Default";
this.solde = 123.45;
this.detecreate = "Detecreate";
}
}
And if you don't want to make your own 'defaults' just leave the constructor empty, to be able to make a "java-default" of your objects.
Upvotes: 0
Reputation: 1488
Most people use an empty constructor without any parameters because they want to be able to construct an empty object. You might want to look into overloading to understand the purpose of such things.
Upvotes: 0