No Param and Default constructors confusion [duplicate] - java

This question already has answers here:
Java default constructor
(13 answers)
Closed 6 years ago.
Here is a code with no param constructor
public class misc2 {
misc2(String x){
}
public static void main(String ... args){
misc2 m = new misc2(); // this throws a compilation error
}
}
My question is why does it throw a compilation error, when Java automatically creates a default constructor, in this case misc2(){...}. if it is not defined already.
Also, now if I add a no param constructor misc2(){...}, which one is actually called by the JVM. Is it the default param or the no param. The second question is because if Java already creates a default constructor with no parameters already, the what is the need to explicitly create a constructor in some cases in the Java program?

Java creates a default constructor if and only if no other explicit constructor is provided.
From the docs:
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
See: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

Related

Java Methods vs constructors parameter comparison [duplicate]

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.

What are the benefits of a zero argument constructor? when is it ideal? [duplicate]

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.

I am creating an empty Java class and compiling it, will any constructor be created [duplicate]

This question already has answers here:
Can a class have no constructor?
(7 answers)
Closed 2 years ago.
I am creating an empty Java class and compiling it, will any constructor be created as it is being compiles successfully
Class ABC{
}
According to Java Documentation ( Providing Constructors for Your Classes ):
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.
It will create a default constructor if no constructor is defined
Also, if we compile your ABC class and decompile the bytecode generated, we will see this code :
public class ABC {
public ABC() {
}
}
So the compiled version have a default constructor
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
So, the compiler will put the default constructor for you if you won't put any constructors.
So your class will be like:
class ABC {
public ABC() {
}
}

What would be the default constructor header [duplicate]

This question already has answers here:
Java default constructor
(13 answers)
Closed 6 years ago.
I am new to java and trying to grasp concepts concerning headers for the default constructor.
The header for the first constructor in Circle is:
public Circle(String label, int radius)
If one decides to add a default constructor to the class. What would be the header for this default constructor?
I have looked online but not really seen a succinct answer.
If one decides to add a default constructor to the class.
You don't decide to add a default constructor. The compiler adds one for you if you don't specify any constructors at all.
The one it adds is defined by JLS§8.8.9:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
The default constructor has the same accessibility as the class (§6.6).
The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
The default constructor has no throws clauses.
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
So if Circle is public, then the default's signature would be:
public Circle()
e.g., the full generated version is:
public Circle() {
super();
}
Keep in mind that the default constructor will only be added if another constructor doesn't already exist. So if the class contains public Circle(String label, int radius), then no default constructor will be added by the compiler. You will have to explicitly add this constructor yourself if you need it.

Declaring Member Class Variables and Instantiating Them [duplicate]

This question already has answers here:
Default constructor vs. inline field initialization
(5 answers)
Closed 9 years ago.
I'm used to C++, where you have to instantiate everything in the constructer, but a recent realization has made me very confused about java. I was just instantiating things in the constructer, and then I realized this syntax was valid:
public class DebateCompetition {
private boolean isAdvanced;
ArrayList<Debate> debates = new ArrayList<Debate>(); //<------
ArrayList<Team> teams;
ArrayList<School> schools;
public void addSchool(School s) {
schools.add(s);
}
}
But that leaves a lot of questions. First: What does it do? Second: When is new ArrayList<Debate>() called? Third: Is this a best practice, or not?
First: What does it do?
All field initializers are executed (in order) before the code in the constructor is executed. (In this case you haven't declared a constructor, so there is a default no-args constructor which invokes the superclasses no-args constructor.)
Second: When is new ArrayList() called?
It is called during the instantiation of a new object.
The call happens after the superclass constructor has completed, and before executing the statements in this classes constructor. (In this case there are no statements in the constructor.)
Third: Is this a best practice, or not?
It is fine.
It's the equivalent of innitializing these variables at the beginning of a constructor. If, in addition, you are using an instance initialization block, they are initialized before the initialization block is invoked. After executing the superclass constructor the order is: fields initialized in the class body, initialization blocks, the constructor body. If you only declare fields in the class body, the compiler automatically initializes them anyway, to their default values: null for Object, false for boolean etc.

Categories