Let’s construct stuff w/ Java

Mehmet Akcay
2 min readFeb 23, 2021
This constructor may have some arguments…

1. Constructors are code blocks that run every time a class is instantiated by using new keyword.

2. No argument constructor is called default constructor.

3. Every class has to have at least one constructor. If no constructor is given in the class definition, compiler will define default constructor for you automatically. If any parametrized constructor is provided, compiler doesn’t declare the default contractor automatically. So it throws a compilation error when you try to use it.

4. Whenever a child class constructor gets invoked, it implicitly invokes the the constructor of parent class unless you explicitly invoke a constructor of the parent class. It’s almost like the compiler puts super(); in the child class constructor.

5. Constructors are not methods. They have no return types.

6. Interfaces don’t have constructors.

7. Abstract classes can have constructors. (But they are generally made protected. Because making them public has no use, since they cannot be called directly, anyway. So you should use the most restricted scope possible next to public which is protected. )

For more info:

  1. http://stackoverflow.com/questions/260666/can-an-abstract-class-have-a-constructor
  2. http://stackoverflow.com/questions/260744/abstract-class-constructor-access-modifier

SuperClassWithNoDefaultConstructor.java

public class SuperClassWithNoDefaultConstructor {

public SuperClassWithNoDefaultConstructor(int a) {
System.out.println(a);
}
}

ConstructorsAreFun.java

public class ConstructorsAreFun extends SuperClassWithNoDefaultConstructor {	int number;
String myName;

//This one will give no errors.
//Because parameterized constructor is called explicitly.
//So default constructor of super
//will not be added implicitly.
public ConstructorsAreFun() {
super(3);
number = 15;
myName = "Default!";
System.out.println("Default is called!");
}

//This one will give the error:
//Implicit super constructor
//SuperClassWithNoDefaultConstructor() is undefined.
//Must explicitly invoke another constructor
public ConstructorsAreFun(int number, String name) {
//implicit super();
this.number = number;
this.myName = name;
System.out.println("My name is " + this.myName);
}
public static void main(String[] args) { ConstructorsAreFun fun = new ConstructorsAreFun(2, "fun");

//Since a parameterized constructor is defined,
//a default constructor will not be added to
//the class definition by compiler.
//So this one will give an error as following:
//The constructor SuperClassWithNoDefaultConstructor() is
//undefined
SuperClassWithNoDefaultConstructor s
= new SuperClassWithNoDefaultConstructor();
}
}

--

--

Mehmet Akcay

a geek who loves to understand the reasons behind things... and colors... Colors are cool.