DEV Community

Cover image for Types of Constructors in Java and Packages in Java – Stop Confusing Default and No-Arg Constructors! - Java Constructor & Package
Kathirvel S
Kathirvel S

Posted on

Types of Constructors in Java and Packages in Java – Stop Confusing Default and No-Arg Constructors! - Java Constructor & Package

Introduction

When beginners start learning Java, two topics often create confusion:

  1. Constructors
  2. Packages

Many students ask:

  • What is a constructor?
  • How many types of constructors exist?
  • Is a default constructor the same as a no-argument constructor?
  • How does Java automatically create constructors?
  • Why do we need packages?
  • How do packages work?
  • How do we compile and run package-based programs?

This guide explains everything from scratch in a beginner-friendly way.


Part 1: Constructors in Java

Official Definition (Oracle Java Documentation)

According to Oracle Java Tutorials:

"A class contains constructors that are invoked to create objects from the class blueprint." ¹

In simple words:

A constructor is a special block of code that runs automatically whenever an object is created.

Think of a constructor as the "setup process" of an object.


Real-Life Example

Imagine buying a new mobile phone.

When the phone is turned on for the first time:

  • Memory is allocated
  • Default settings are loaded
  • Language is selected
  • System gets initialized

Similarly, when an object is created in Java:

Student s1 = new Student();
Enter fullscreen mode Exit fullscreen mode

Java allocates memory and calls the constructor to initialize the object.


Characteristics of Constructors

A constructor:

✔ Has the same name as the class

✔ Has no return type

✔ Runs automatically when an object is created

✔ Can accept parameters

✔ Can be overloaded

✔ Cannot be static

✔ Cannot be abstract (TBD)

✔ Cannot be final (TBD)


Example

class Student {

    Student() {
        System.out.println("Constructor Called");
    }

    public static void main(String[] args) {

        Student s = new Student();

    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Constructor Called
Enter fullscreen mode Exit fullscreen mode

Notice:

Student()
Enter fullscreen mode Exit fullscreen mode

has the same name as the class.


Why Do We Need Constructors?

Without constructors:

Student s = new Student();

s.name = "John";
s.age = 20;
Enter fullscreen mode Exit fullscreen mode

You would need to initialize everything manually.

Constructors allow initialization during object creation itself.

Student s = new Student("John",20);
Enter fullscreen mode Exit fullscreen mode

Much cleaner.


Types of Constructors in Java

Most beginner courses discuss:

  1. Default Constructor
  2. No-Argument Constructor
  3. Parameterized Constructor

Additionally, constructor overloading is an important concept.

Let's study each deeply.


1. Default Constructor

This is one of the most misunderstood topics in Java.


Official Definition

Oracle documentation explains that if a class contains no constructors, the compiler automatically provides one. ¹


What is a Default Constructor?

A default constructor is a constructor automatically created by the Java compiler when you do not write any constructor.

Example:

class Student {

}
Enter fullscreen mode Exit fullscreen mode

You wrote:

class Student {

}
Enter fullscreen mode Exit fullscreen mode

But Java internally behaves like:

class Student {

    Student() {

    }

}
Enter fullscreen mode Exit fullscreen mode

The compiler secretly creates it.


Why Does Java Create It?

Imagine this code:

Student s = new Student();
Enter fullscreen mode Exit fullscreen mode

Java needs some constructor to execute.

Since you didn't provide one, Java generates one automatically.


What Does the Default Constructor Do?

The generated constructor:

  1. Calls parent constructor using super()
  2. Initializes object fields with default values

Example:

class Student {

    int id;
    String name;

}
Enter fullscreen mode Exit fullscreen mode

Object creation:

Student s = new Student();
Enter fullscreen mode Exit fullscreen mode

Values become:

id = 0
name = null
Enter fullscreen mode Exit fullscreen mode

These are Java's default field values.


Internal View

Compiler-generated constructor roughly looks like:

Student() {
    super();
}
Enter fullscreen mode Exit fullscreen mode

Important Rule

Java generates a default constructor ONLY IF NO CONSTRUCTOR EXISTS.

Example:

class Student {

    Student(int id){

    }

}
Enter fullscreen mode Exit fullscreen mode

Now:

Student s = new Student();
Enter fullscreen mode Exit fullscreen mode

Error!

Why?

Because Java sees that you already created a constructor.

Therefore it does not generate the default constructor.


2. No-Argument Constructor

Now comes the most confusing interview question.


What is a No-Argument Constructor?

A constructor that accepts zero parameters.

Example:

class Student {

    Student() {
        System.out.println("No Arg Constructor");
    }

}
Enter fullscreen mode Exit fullscreen mode

No parameters.

Hence:

Student()
Enter fullscreen mode Exit fullscreen mode

is a no-argument constructor.


Is Default Constructor Equal to No-Argument Constructor?

Short Answer:

NO.

They are related but not identical.


Difference Table

Feature Default Constructor No-Argument Constructor
Created By Java Compiler Programmer
Parameters None None
Written by User No Yes
Automatic Yes No

Example 1: Default Constructor

class Student {

}
Enter fullscreen mode Exit fullscreen mode

Compiler creates:

Student() {

}
Enter fullscreen mode Exit fullscreen mode

This is a DEFAULT constructor.


Example 2: No-Argument Constructor

class Student {

    Student() {
        System.out.println("Created");
    }

}
Enter fullscreen mode Exit fullscreen mode

This is a NO-ARGUMENT constructor.


Easy Rule to Remember

Every default constructor is a no-argument constructor.

BUT

Not every no-argument constructor is a default constructor.

Why?

Because default constructors are compiler-generated.

No-arg constructors are programmer-written.


Interview Question

Question:

Is default constructor same as no-arg constructor?

Best Answer:

No.

A default constructor is automatically provided by the Java compiler when no constructor exists in the class.

A no-argument constructor is explicitly written by the programmer and takes no parameters.


3. Parameterized Constructor

Official Definition

W3Schools states that constructors can take parameters that initialize object attributes. ²


What is a Parameterized Constructor?

A constructor that receives values while creating objects.

Example:

class Student {

    String name;
    int age;

    Student(String name,int age){

        this.name = name;
        this.age = age;

    }

}
Enter fullscreen mode Exit fullscreen mode

Object Creation

Student s1 = new Student("John",20);
Enter fullscreen mode Exit fullscreen mode

Values become:

name = John
age = 20
Enter fullscreen mode Exit fullscreen mode

Why Use Parameterized Constructors?

Without constructor:

Student s = new Student();

s.name="John";
s.age=20;
Enter fullscreen mode Exit fullscreen mode

With constructor:

Student s = new Student("John",20);
Enter fullscreen mode Exit fullscreen mode

Cleaner and safer.


Constructor Overloading

Java allows multiple constructors.

Example:

class Student {

    Student() {

    }

    Student(String name) {

    }

    Student(String name,int age) {

    }

}
Enter fullscreen mode Exit fullscreen mode

Java selects constructor based on arguments.

new Student();
new Student("John");
new Student("John",20);
Enter fullscreen mode Exit fullscreen mode

This is constructor overloading.


Constructor Chaining (TBD)

One constructor can call another constructor.

Example:

class Student {

    Student() {

        this("Unknown");

    }

    Student(String name){

        System.out.println(name);

    }

}
Enter fullscreen mode Exit fullscreen mode

Output:

Unknown
Enter fullscreen mode Exit fullscreen mode

This improves code reuse.


Summary of Constructors

  • Constructor initializes objects.
  • Constructor name must match class name.
  • No return type.
  • Runs automatically.
  • Default constructor is compiler-generated.
  • No-arg constructor is programmer-written.
  • Parameterized constructor accepts values.
  • Constructors can be overloaded.

Part 2: Packages in Java

Now let's move to another important topic.


What is a Package?

Official Definition

According to Oracle:

"A package is a namespace that organizes a set of related classes and interfaces." ³


Beginner-Friendly Definition

A package is a folder-like structure used to organize Java classes.

Think about your computer.

Without folders:

1000 files in one place
Enter fullscreen mode Exit fullscreen mode

Very messy.

Folders solve this problem.

Packages do the same in Java.


Why Do We Need Packages?

Imagine a company with:

5000 Java classes
Enter fullscreen mode Exit fullscreen mode

Without packages:

Student.java
Employee.java
Manager.java
Account.java
Admin.java
Enter fullscreen mode Exit fullscreen mode

Everything mixed together.

Hard to manage.

Packages provide organization.


Advantages of Packages

1. Organization

Classes stay grouped.

Example:

com.company.student
com.company.employee
com.company.finance
Enter fullscreen mode Exit fullscreen mode

2. Avoid Name Conflicts

Two developers may create:

Student
Enter fullscreen mode Exit fullscreen mode

class.

Packages allow:

college.Student
Enter fullscreen mode Exit fullscreen mode

and

school.Student
Enter fullscreen mode Exit fullscreen mode

Both can exist.


3. Access Control

Packages help control visibility.

Keywords:

public
protected
default
private
Enter fullscreen mode Exit fullscreen mode

work together with packages.


Package Syntax

package mypackage;
Enter fullscreen mode Exit fullscreen mode

Must be the first statement.

Example:

package mypackage;

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

Creating Your First Package

Folder structure:

project
|
|-- mypackage
      |
      Student.java
Enter fullscreen mode Exit fullscreen mode

Student.java

package mypackage;

public class Student {

    public void show(){

        System.out.println("Hello Package");

    }

}
Enter fullscreen mode Exit fullscreen mode

Using Package Class

import mypackage.Student;

public class Main {

    public static void main(String[] args){

        Student s = new Student();

        s.show();

    }

}
Enter fullscreen mode Exit fullscreen mode

Import Keyword (TBD)

Used to access classes from other packages.

Syntax:

import packageName.ClassName;
Enter fullscreen mode Exit fullscreen mode

Example:

import mypackage.Student;
Enter fullscreen mode Exit fullscreen mode

Import All Classes

import java.util.*;
Enter fullscreen mode Exit fullscreen mode

The * means all classes.

Example:

ArrayList
Scanner
HashMap
Enter fullscreen mode Exit fullscreen mode

can be used.


Common Java Packages

java.lang

Imported automatically.

Contains:

String
System
Math
Object
Enter fullscreen mode Exit fullscreen mode

java.util

Contains:

ArrayList
Scanner
HashMap
Collections
Enter fullscreen mode Exit fullscreen mode

java.io

Contains:

File
BufferedReader
PrintWriter
Enter fullscreen mode Exit fullscreen mode

How Java Stores Packages

Package:

package com.company.student;
Enter fullscreen mode Exit fullscreen mode

creates structure:

com
 |
 company
   |
 student
Enter fullscreen mode Exit fullscreen mode

Java expects folder names to match package names.


Compiling Packages

This is where beginners get confused.

Suppose:

package mypackage;

public class Student {

}
Enter fullscreen mode Exit fullscreen mode

File:

Student.java
Enter fullscreen mode Exit fullscreen mode

Compile:

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

What Does -d Mean?

-d means destination directory.

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

means:

"Create package folders in current directory."

Output:

mypackage
 |
 Student.class
Enter fullscreen mode Exit fullscreen mode

Running Package Programs

Compile:

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

Run:

java mypackage.Student
Enter fullscreen mode Exit fullscreen mode

Notice:

java Student
Enter fullscreen mode Exit fullscreen mode

❌ Wrong

java mypackage.Student
Enter fullscreen mode Exit fullscreen mode

✅ Correct


Example

File:

package mypackage;

public class Student {

    public static void main(String[] args){

        System.out.println("Hello Package");

    }

}
Enter fullscreen mode Exit fullscreen mode

Compile:

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

Run:

java mypackage.Student
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Package
Enter fullscreen mode Exit fullscreen mode

Package Naming Convention

Usually:

com.company.project
Enter fullscreen mode Exit fullscreen mode

Examples:

com.google
com.microsoft
com.amazon
org.apache
Enter fullscreen mode Exit fullscreen mode

Reverse domain naming prevents conflicts.


Real Industry Example

Spring Framework:

org.springframework
Enter fullscreen mode Exit fullscreen mode

Hibernate:

org.hibernate
Enter fullscreen mode Exit fullscreen mode

JUnit:

org.junit
Enter fullscreen mode Exit fullscreen mode

Large projects may contain hundreds of packages.


Final Summary

Constructors:

  • Special methods used for initialization.
  • Run automatically during object creation.
  • Types:

    • Default Constructor
    • No-Argument Constructor
    • Parameterized Constructor
    • Constructor Overloading

Important:

  • Default constructor is generated by compiler.
  • No-arg constructor is written by programmer.
  • Every default constructor is a no-arg constructor.
  • Not every no-arg constructor is a default constructor.

Packages:

  • Organize Java classes.
  • Prevent naming conflicts.
  • Improve maintainability.
  • Support access control.
  • Created using package keyword.
  • Accessed using import keyword.

Compile package:

javac -d . Student.java
Enter fullscreen mode Exit fullscreen mode

Run package:

java mypackage.Student
Enter fullscreen mode Exit fullscreen mode

References

  1. Oracle Java Tutorials – Constructors:
    https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

  2. W3Schools – Java Constructors:
    https://www.w3schools.com/java/java_constructors.asp

  3. Oracle Java Tutorials – Packages:
    https://docs.oracle.com/javase/tutorial/java/package/index.html

  4. W3Schools – Java Packages:
    https://www.w3schools.com/java/java_packages.asp

  5. Java Language Specification (JLS):
    https://docs.oracle.com/javase/specs/

  6. Oracle Java Documentation:
    https://docs.oracle.com/en/java/

Top comments (0)