Constructor, this keyword, Packages...
Chithra Priya

Chithra Priya @chithra_priya

Joined:
Apr 29, 2025

Constructor, this keyword, Packages...

Publish Date: Jul 22
1 0

Difference between zero argument constructor and default constructor in Java?

Default Constructor:**

  • A constructor that is automatically provided by the Java compiler when no constructor is defined in the class.
  • It has no parameters (zero-arguments) and no body code.
  • It initializes instance variables to default values (e.g., 0 for int, null for objects).

Example:

public class MyClass {

}
Enter fullscreen mode Exit fullscreen mode

Zero-Argument Constructor:

  • A constructor that is explicitly written by the programmer with no parameters.
  • It has no parameters, it is not considered a default constructor, because it's written by developer. Example:
public class MyClass {
    MyClass() {
        System.out.println("zero-argument constructor");
    }
}
Enter fullscreen mode Exit fullscreen mode

This:

  • This is a keyword.
  • This refers to current object.It is used to define global variable.
  • This keyword is used to differentiate between local and global variable.
  • When local variable names are the same as instance variables, this is used to differentiate.

Example:

public class Student {
    String name;

    public Student(String name) {
        this.name = name; 
    }
}
Enter fullscreen mode Exit fullscreen mode

Package:

In java package means folder.

Why Use Packages in Java?

  • Grouping similar file.
  • Avoid naming conflict.

Create package:
package com.indianBank;

Compile package:
javac -d . classname.java

Run package:
java filename

Comments 0 total

    Add comment