In Java, both constructors and methods are blocks of code defined within a class, but they serve distinct
purposes and have different characteristics:
Constructors:
Purpose: Constructors are special methods used to initialize objects when they are created. Their primary
role is to set the initial state (values of instance variables) of a newly created object.
Name: A constructor's name must be exactly the same as the class name.
Return Type: Constructors do not have a return type, not even void.
Invocation: They are implicitly invoked by the Java Virtual Machine (JVM) when an object is created
using the new keyword.
Inheritance: Constructors are not inherited by subclasses. A subclass must define its own constructors.
Existence: A class can have multiple constructors (overloading) with different parameter lists. If no
constructor is explicitly defined, the Java compiler provides a default no-argument constructor.
Methods:
Purpose:
Methods define the behavior or functionality of an object. They perform specific tasks or operations on
an object's data.
Name:
Method names can be any valid identifier, and they do not have to match the class name.
Return Type:
Methods must have a return type (which can be void if no value is returned).
Invocation:
They are explicitly invoked by calling them on an object or class (for static methods).
Inheritance:
Methods can be inherited by subclasses and can also be overridden.
Existence:
A class can have multiple methods with the same name (overloading) as long as their parameter lists
differ. Methods are optional; a class may or may not have any methods.
class Geek {
// static int num;
// static String name;
int num;
String name;
// This would be invoked while an object of that class created.
Geek()
{
num=10;
name="xyz";
System.out.println("Constructer called : "+", Num value : "+num+", Name Value : "+name);
}
public static void main(String[] args)
{
// new Geek();
System.out.println("Geek Class is executed ");
// Works if num and Name are declared as Static
// System.out.println("In main() method : "+", Num value : "+num+", Name Value : "+name);
}
}
class GFG {
public static void main(String[] args)
{
// this would invoke default constructor.
Geek geek1 = new Geek();
// Default constructor provides the default
// values to the object like 0, null
System.out.println("Called Name from GFG Class : "+geek1.name);
System.out.println("Called Num from GFG Class : "+geek1.num);
}
}