Last Updated on 14 August 2019   |   Print Email
In this article, you will learn some rules regarding constructors in Java.We all know that an object is an instance of a specific class. To create an object, we use the new keyword, for example:
Dog myDog = new Dog("Rex");
Here, we create a new Dog object and specify its name is ‘Rex’. The String ‘Rex’ is passed as an argument to the following constructor of the Dog class:
Dog(String name) {
this.name = name;
}
We can see that this constructor allows us to specify name of the dog when creating the object.A constructor is a special code block of a class. It is always invoked when a new instance of the class is created. In other words, constructors are used to initialize state of an object when the object is being created.We can see that constructors look like methods but they are totally different:
Constructors have same name as the class name.
Constructors have a parameter list like methods but don’t have a return type, nor even void.
For basic about constructors, you can refer to the Java Tutorials: Providing Constructors for Your ClassesNow, let’s go through some important rules regarding constructors in the Java programming language.
1. Constructors can be overloaded:
This means a class can have many constructors as long as their parameters lists are different. For example:
Here, the Cat class has 3 different constructors, thus we can create new Cat objects in 3 different ways:
Cat cat1 = new Cat();
Cat cat2 = new Cat("Miumiu");
Cat cat3 = new Cat("Kitty", "white");
2. Default constructor:
Declaring constructors is not required. When we don’t supply any constructor, the Java compiler automatically generates a default constructor which is empty and has no parameters.For example, if we write the Dog class as follows:
class Dog {
void bark() { }
void waveTail() { }
}
Then the compiler will insert a default constructor like this:
Dog() {
}
3. The compiler won’t generate the default constructor if there’s a already constructor in the class:
Consider the following Dog class:
class Dog {
String name;
Dog(String name) {
this.name = name;
}
}
Here, the Dog class has the constructor Dog(String name) then there is no default constructor. If we try to create a Dog object like this:
Dog myDog = new Dog();
Then the compiler will issue an error because it couldn’t find the no-argument constructor.
4. The default constructor is only generated by the compiler:
If we explicitly write a constructor that looks exactly the same as the default constructor, it is NOT called the default constructor.
5. Constructors are not inherited:
Unlike methods in a superclass can be inherited by subclasses, constructors are not inherited. Consider the following example:
class Rectangle {
Rectangle(int width, int height) { }
}
class Square extends Rectangle {
}
We can’t do something like this:
Square box = new Square(10, 10);
6. Constructors can be private!
Yes, this is true. We can make a constructor private to prevent the outside world from creating a new instance of our class. Consider the following class with a private constructor:
class SpecialDog {
private SpecialDog() {
}
}
Oh, what is the benefit of private constructor?In a design pattern called Singleton pattern, private constructor is used to ensure there is always one instance of the class exists. The singleton class provides a static method for obtaining this unique instance.
7. The default constructor has same access modifier as the class:
If we declare a class like this:
public class Dog { }
Then the compiler will insert the default constructor with the same access modifier:
public Dog() { }
8. A constructor calls the default constructor of its superclass:
The Java compiler automatically inserts a call to super()at the first line in the constructor. Consider the following two classes:
class Parent {
Parent(int number) {
}
}
class Child extends Parent {
Child() {
}
}
Here, the code doesn’t get compiled because the compiler inserts a call to super() in the Child’s constructor:
Child() {
super(); // auto-inserted by the compiler
}
But the Parent class has no such default constructor, thus the compiler issues a compile error. So pay attention to this rule when extending a parent class.
9. The first statement in a constructor must call to this() or super():
The first statement of every constructor must be a call to either this() (an overloaded constructor) or super(). For example:
class Super {
Super(int x) { }
}
class Sub extends Super {
int y;
Sub(int x) {
super(x);
y = x;
}
Sub(int x, int y) {
this(x);
}
}
So far I have rounded up some important rules regarding constructors in Java. So remember to apply these rules into your daily coding.If you have any questions or complements, feel free to let me know in the comments section.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
I have heard a lot of videos on java constructors, but no where was mentioned constructors cannot be inherited in the sublclass.Also that the first default call in a constructor is to default superclass constructor or to this (). Thanks a lot for the in depth material, this cleared some of the doubtds iwas having.
Q2. If we are doing this "Dog myDog = new Dog("Rex");" then do we need a constructor. Can't myDog be assigned with the value "Rex" without making the parametrised constructor?
Comments
Q2. If we are doing this "Dog myDog = new Dog("Rex");" then do we need a constructor. Can't myDog be assigned with the value "Rex" without making the parametrised constructor?
Q3. Why do constructors not have a return type?