Skip to main content

Command Palette

Search for a command to run...

Java Methods and Constructors: A Comprehensive Guide

Published
7 min read
N
Java & Spring Boot learner | Writing beginner-friendly technical articles | Exploring backend development

Introduction to Methods:

In Java, methods are used to define reusable blocks of code that perform a specific task. Instead of writing the same logic multiple times, methods allow us to write it once and reuse it whenever needed, improving code readability and maintainability.

What is a Method ?

  • Methods are a set of instructions that perform a specific task.

  • Methods help in breaking a large program into smaller, manageable pieces of code, which makes debugging and testing easier.

  • They also support important object-oriented concepts such as abstraction and code reusability.

How to declare Method?

Example:

public int sum(int a, int b){
 return a+b;
}

Here,

  • public → Access Specifier

  • int → Return Type

  • sum → Method name

  • int a, int b → Method arguments, also called as parameters

  • Also, this is a user defined method.

Access Specifiers:

Defines accessibility of a method. It defines Where we can use the methods. There are 4 access specifiers, They are:

  1. public: Can be accessed through any class in any package

  2. private: Can be accessed by methods only in the same class.

  3. protected: Can be accessed by other classes in same package or other sub classes in different package.

  4. default: Can be accessed by classes in the same package. If we have not mentioned anything, then it can be considered as default access specifier by java. Also it is called as package-private.

Return Type:

It tells what type the method will return after execution of method. If the method doesn’t return anything then void is used. Also we can use class name or primitive data types as return type of the method.

Method-name:

It should be verb or that it specify some action that it performs. It should start with small letter and follow camelCase in case of multiple words.

Method Parameters:

It is a list of variables that will be used in the method, also known as parameters. There can be methods with parameters and without parameters.

Method Body:

Method body get finished when you call return inside the opening and closing blocks{}. It’s scope will be from starting {, and it executes the set of instructions , if return or break keyword found it stop executing the further statements and come out of the },method body.

Types of Methods:

System defined Methods:

It is also called as built-in methods, which are already defined and ready to use in Java like Math.pow(), Math.sqrt(). Also to use this pre-defined methods we have to import the necessary packages.

User defined method:

Methods which are created by the programmer or user is known as User defined method.

Overloaded method:

In a program, when there is more than one method with the same name, with different parameters is known as overloaded method. Also called as method overloading.

Overloaded method - Example

public class Addition{
  public int sum(int a , int b){
    return a + b;
   }
  public int sum(int a, int b, int c){
    return a+b+c;
   }
  public float sum(float a, float b){
    return a+b;
  }
}

Here the method names should be same irrespective of access specifier and return type. And parameters must and should not be repeated, either there should be change in data types or order of sequence of parameters.

Overridden method:

Subclass / child class has the same method as the parent class. The method can be executed based on the object created and the decision can be taken by the compiler at runtime.

Overridden method - Example

--------Parent class ----------
public class Fruit {
  public void apple(){
   System.out.println("Apple");
 }
}
-------- Child class --------------
public class Kiwi extends Fruit {
  @Overridden
  public void apple(){
   System.out.println("Kiwi");
}
}

------- Main class -------------
public class Main{
  public static void main(String[] args){
     Fruit fruitObj = new Kiwi();
     fruitobj.apple();
  }
}

Here the Kiwi class object is created and it is a sub class of Fruit class, the methods and variables present in the Fruit class can be accessed by the sub class. And after creating the object we called the method apple(), so apple method can be executed, Here compiler calls the apple() of class Kiwi. It is decided at run time. This is called as Method Overriding.

Static methods:

These methods are associated with the class, can be called just with class name. Static methods cannot access non static instance variables and methods and static methods cannot be overridden.

When to declare static methods:

Methods which do not modify the stack of the object can be declared static, utility method which do not use any instance variable and compute only an arguments.

Example: Factory Design Pattern.

Final methods:

Final method cannot be overridden in Java. It is so because final method means its implementation cannot be changed. If child class cannot change the present implementation then we declare the method as final.

Abstract method:

This method can be declared in abstract classes and interfaces. A method which has only declaration but no implementation then we call it is abstract method. Abstract methods can be implemented in sub classes.

Variable arguments (Var-args):

It is used when we don’t know the number of arguments. So, there can be variable number of inputs in the parameter, and only one variable argument can be present in the method and it should be the last argument in the parameter list.

Example of Var-args:

public int sum(int ...variable){
 // implementation
}

Introduction to Constructors:

In Java, a constructor is a special member of a class that is used to initialize objects. It is automatically called when an object of a class is created and is mainly used to assign initial values to instance variables. A strong understanding of constructors helps in managing object creation effectively and plays an important role in object-oriented programming and real-world Java applications.

What is constructor?

Constructor is a special non-static method. And constructor name should be same name as class name and it doesn’t have return type. Constructor cannot be static or final or abstract, synchronized. Here, new keyword is used to call the constructor.

Why constructor name is same as of class name?

Constructor name is always same as class name because it is easy to identify and there is no return type because implicitly java adds class as return type.

Why constructor do not have return type?

There can be methods with same name and even class as return type but they cannot be called constructors as they do not obey the rules of constructor is same name without return type.

Why constructor cannot be final?

Constructors are different from used methods and cannot be inherited. So, it doesn’t make sense to make them final because final is used to prevent overriding, if constructors cannot be inherited then there is no use for making it final.

Why constructor cannot be static?

Since static methods can only access static variables and other static methods, so it won’t be able to initialize the instance variable. we also won’t be able to use constructor chaining and call super().

Can we define constructor in interface?

We cannot create object for interfaces so, It is not possible to define constructors.

Types of constructors:

Default constructor

When we do not define a constructor in program, then java internally provides a constructor which is known as default constructor.

No Argument constructor

A constructor which is defined by user without any parameters, then it is called as no argument constructor.

Parameterized constructor

A constructor which is defined by user with parameters, it takes arguments and assign instance variables with those parameters. We can initialize one or multiple instance variable using a parameterized constructor.

Constructor overloading

In Java , we can create multiple constructors with different parameters so constructor overloading is possible.

Private constructor

In Java, we can create a private constructor and no one outside the class will be able to call the constructor, This is used usually in singleton design pattern, To create an object of a class having private constructor. We can create another static method to create the object and then call that method using class name.

Constructor chaining

It refers to calling one constructor from another constructor. This is done by suing this() and super().

Example for Constructor chaining

public class Student{
   String name;
   int sId;
   Student(){
    this(10);
   }
   Student(int sId){
      this("nandini", sId);
   }
   Student(String name, int sId){
         this.name=name; 
         this.sId=sId;
   }
}

Here, we called other constructor within a constructor using this().

Using super()

The constructor of a child class always Invokes the constructor of parent class first and then invokes its own constructor. This is done using super(), so if we explicitly don’t add super() in child constructor then Java adds it internally. So this() and super() are used for constructor chaining.

If the parent class has a parameterized constructor, then we’ll have to mandatorily pass an argument to super() to call the parent class is parameterized constructor.

Conclusion

Methods and constructors are fundamental building blocks of Java programming and play a vital role in writing clean, structured and object-oriented code. Building clarity in these basics paves the way for advanced topics like inheritance, polymorphism, and memory management.

More from this blog

CoreJava

19 posts

I have written and published a comprehensive blog series titled "CoreJava" on Hashnode, based on my learning journey from basics to advanced. The series includes topics like OOP, Collections, Exception Handling, Multithreading, and Java Streams, explained with clear examples and practical insights to help learners build a strong foundation in java.