Compiler Rules for Class Construction in Java

Thanoshan MV
2 min readMay 30, 2020

--

Photo by Anna Earl on Unsplash

Objects in Java are created from inside out.

It goes all the the way up to the Object class, comes down through the hierarchy and initializes all instance variables to create objects.

public class Person {
private String name;
}

In the above code, there is no statement that the Person extends Object but when creating an object, it actually goes inside out. How?

Compiler Rule 1

When you don’t define a super class, the compiler inserts one for you.

While compiling this is what actually happens:

public class Person extends Object{
private String name;
}

Now we know how Person extends Object.

Let’s say we have defined a super class for Person then what happens?

public class Person extends Alien{
private String name;
}

Since there is a super class inserted, the compiler will not do anything.

Now we know how Person extends Object but how the Object class constructor is called?

Compiler Rule 2

When you don’t define a constructor, the compiler inserts default constructor for you.

public class Person extends Object{
private String name;
public Person(){

}

}

Compiler Rule 3

For all constructors in Java, the first statement of them should be either calling same class constructor or super class constructor ( this() or super() ).

Otherwise Java will insert super(). It will call the super class no argument constructor.

So, the above example code will be compiled like here:

public class Person extends Object{
private String name;
public Person(){
super();
}

}

NOTE: When we define constructor explicitly the compiler will not add the default constructor for us.

Conclusion

These are the compiler rules for class construction. They allow the object to be created from inside out.

Thank you for reading!

--

--

Thanoshan MV
Thanoshan MV

Written by Thanoshan MV

Hi! I'm a Software Engineer with a passion for research in AI, software engineering, and open-source development. Web - https://thanoshanmv.github.io/

No responses yet