Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task. It provides the reusability of code. We can also
easily modify code using methods. In this section, we will learn what is a method in Java, types
of methods, method declaration, and how to call a method in Java.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.
The most important method in Java is the main() method. If you want to read more about the
main() method, go through the link [Link]
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
Public: The method is accessible by all classes when we use public specifier in our application.
Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked by its
name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left the
parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with a
lowercase letter. If the method name has more than two words, the first name must be a verb
followed by adjective or noun. In the multi-word method name, the first letter of each word must
be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it
is known as method overloading.
Types of Method
There are two types of methods in Java:
i. Predefined Method
ii. User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program at any point. Some pre-
defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the
predefined methods in our program, a series of codes related to the corresponding method runs in
the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the [Link] class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Let's see an example of the predefined method.
[Link]
public class Demo
public static void main(String[] args)
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
Output:
The maximum number is: 9
In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max() method
is a method of the Math class that returns the greater of two numbers.
We can also see the method signature of any predefined method by using the link
[Link] When we go through the link and see the max() method signature, we
find the following:
In the above method signature, we see that the method signature has access specifier public,
nonaccess modifier static, return type int, method name max(), parameter list (int a, int b). In the
above example, instead of defining the method, we have just invoked the method. This is the
advantage of a predefined method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will define the
method.
//user defined method public static
void findEvenOdd(int num)
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
}
We have defined the above method named findevenodd(). It has a parameter num of type int. The
method does not return any value that's why we have used void. The method body contains the
steps to check the number is even or odd. If the number is even, it prints the number is even, else
prints the number is odd.
How to Call or Invoke a User-defined Method
Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the called
method.
import [Link];
public class EvenOdd
public static void main (String args[])
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the control
transfer to the method and gives the output accordingly.
Let's combine both snippets of codes in a single program and execute it.
[Link]
import [Link];
public class EvenOdd
public static void main (String args[])
//creating Scanner class object
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from user
int num=[Link]();
//method calling
findEvenOdd(num);
//user defined method public static
void findEvenOdd(int num)
//method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd
Let's see another program that return a value to the calling method.
In the following program, we have defined a method named add() that sum up the two numbers.
It has two parameters n1 and n2 of integer type. The values of n1 and n2 correspond to the value
of a and b, respectively. Therefore, the method adds the value of a and b and store it in the
variable s and returns the sum.
[Link]
public class Addition
public static void main(String[] args)
int a = 19;
int b = 5;
//method calling int c = add(a, b); //a and b
are actual parameters
[Link]("The sum of a and b is= " + c);
}
//user defined method public static int add(int n1, int n2) //n1
and n2 are formal parameters
int s;
s=n1+n2; return s;
//returning the sum
Output:
The sum of a and b is= 24
Static Method
A method that has static keyword is known as static method. In other words, a method that
belongs to a class rather than an instance of a class is known as a static method. We can also
create a static method by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can
access static data members and also change the value of it. It is used to create an instance
method. It is invoked by using the class name. The best example of a static method is the main()
method.
Example of static
method [Link]
public class Display
public static void main(String[] args)
show();
static void show()
[Link]("It is an example of static method.");
Output:
It is an example of a static method.
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in the
class. Before calling or invoking the instance method, it is necessary to create an object of its
class. Let's see an example of an instance method. [Link] public class
InstanceMethodExample
public static void main(String [] args)
//Creating an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
[Link]("The sum is: "+[Link](12, 13));
int s;
//user-defined method because we have not used static keyword
public int add(int a, int b)
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25
There are two types of instance method:
Accessor Method
Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor
method. We can easily identify it because the method is prefixed with the word get. It is also
known as getters. It returns the value of the private field. It is used to get the value of the private
field.
Example
public int getId()
return Id;
}
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can
easily identify it because the method is prefixed with the word set. It is also known as setters or
modifiers. It does not return anything. It accepts a parameter of the same data type that depends
on the field. It is used to set the value of the private field.
Example
public void setRoll(int roll)
[Link] = roll;
Example of accessor and mutator method
[Link]
public class Student
private int roll;
private String name; public int
getRoll() //accessor method
return roll;
public void setRoll(int roll) //mutator method
[Link] = roll;
public String getName()
return name;
public void setName(String name)
[Link] = name;
public void display()
{
[Link]("Roll no.: "+roll);
[Link]("Student name: "+name);
Abstract Method
The method that does not has method body is known as abstract method. In other words, without
an implementation is known as abstract method. It always declares in the abstract class. It means
the class itself must be abstract if it has abstract method. To create an abstract method, we use
the keyword abstract. Syntax abstract void method_name();
Example of abstract method
[Link] abstract class Demo
//abstract class
//abstract method declaration
abstract void display();
public class MyClass extends Demo
{
//method impelmentation
void display()
[Link]("Abstract method?");
public static void main(String args[])
//creating object of abstract class
Demo obj = new MyClass();
//invoking abstract method
[Link]();
Java void Keyword
A method without any return values:
Example
public class Main {
static void myMethod() {
[Link]("I just got executed!");
public static void main(String[] args) {
myMethod();
Definition and Usage
The void keyword specifies that a method should not have a return value.
Tip: If you want a method to return a value, you can use a primitive data type (such as int, char,
etc.) instead of void, and use the return keyword inside the method:
Example
public class Main {
static int myMethod(int x) {
return 5 + x;
}
public static void main(String[] args) {
[Link](myMethod(3));
// Outputs 8
Pass by Value in Java
In Java, all method arguments are passed by value. This means when you pass a variable to a
method, Java passes a copy of the variable's value, not the original reference itself. Any changes
made to the parameters inside the method do not affect the original variable.
Key Points:
1. Primitive Data Types: When passing a primitive type (like int, float, double, etc.) to a
method, the method gets a copy of the value. Any changes to this value inside the method
do not affect the original value outside the method.
2. Objects: When passing an object to a method, the method still receives a copy of the
reference to the object. The reference itself is passed by value, so any changes made to the
object's fields inside the method will reflect outside. However, if you change the reference
itself (make it point to another object), it won't affect the original object reference outside
the method.
Simple Example of Pass by Value with Primitive Types:
public class PassByValueExample {
public static void main(String[] args) {
int num = 10;
// Print original value
[Link]("Before method call: " + num); // Output: 10
// Call the method
modifyValue(num);
// Print value after method call
[Link]("After method call: " + num); // Output: 10
// Method that attempts to modify the passed variable
public static void modifyValue(int value) {
value = 50; // Modify the value
[Link]("Inside method: " + value); // Output: 50
}
}
Explanation:
The variable num is passed to the method modifyValue().
Inside the method, the parameter value is modified to 50.
However, when we return to the main() method, the original value of num remains
unchanged because Java passed a copy of the value (10), not the actual variable.
Example of Pass by Value with Objects:
class Dog {
String name;
Dog(String name) {
[Link] = name;
public class PassByValueObjects {
public static void main(String[] args) {
Dog myDog = new Dog("Buddy");
// Print original name
[Link]("Before method call: " + [Link]); // Output: Buddy
// Call the method
modifyDog(myDog);
// Print name after method call
[Link]("After method call: " + [Link]); // Output: Max
public static void modifyDog(Dog dog) {
// Changing the object’s field
[Link] = "Max"; // Modifies the original object's field
[Link]("Inside method: " + [Link]);
// Output: Max
Explanation:
The object myDog is passed to the method modifyDog().
Inside the method, we modify the field name of the dog object.
When we return to the main() method, the change to the name field is reflected because
the method received a copy of the reference to the same object. Changes to the object's
internal state persist.
NOTE
[Link] = name;
[Link]: The this keyword refers to the current instance of the Dog object being
created. It helps differentiate between the instance variable name of the class and the
parameter name passed to the constructor.
The code [Link] = name; assigns the value of the parameter name to the instance
variable name of the Dog object. This ensures that the dog's name is stored in the object.
Without this, it would be ambiguous whether you're referring to the instance variable name or
the parameter name.
Key Takeaways:
Pass by Value for Primitives: The original variable remains unchanged outside the
method.
Pass by Value for Objects: The object's reference is passed by value, but changes to the
object's internal fields are reflected outside the method because both the original and the
method's parameter refer to the same object. However, if the reference itself is reassigned,
it won't affect the original reference.
Method Overloading
Definition:
Method overloading allows multiple methods in the same class to have the same name but differ
in their parameter lists (number or types of parameters). It enables a method to perform different
tasks based on the arguments passed to it.
Example of Method Overloading
1. Two-parameter method:
static int max(int firstIn, int secondIn) {
if (firstIn > secondIn) {
return firstIn;
} else {
return secondIn;
o Purpose: Returns the greater of two integers.
2. Three-parameter method:
static int max(int firstIn, int secondIn, int thirdIn) {
int result = firstIn;
if (secondIn > result) {
result = secondIn;
}
if (thirdIn > result) {
result = thirdIn;
return result;
o Purpose: Returns the greatest of three integers.
COMPLETE CODE
public class MaxOverloadingDemo {
// Method to return the greater of two integers
static int max(int firstIn, int secondIn) {
if (firstIn > secondIn) {
return firstIn;
} else {
return secondIn;
}
}
// Method to return the greatest of three integers
static int max(int firstIn, int secondIn, int thirdIn) {
int result = firstIn; // Start by assuming the first number is the greatest
if (secondIn > result) {
result = secondIn; // Update result if the second number is greater
if (thirdIn > result) {
result = thirdIn; // Update result if the third number is greater
return result;
public static void main(String[] args) {
// Demonstrate the use of the two-parameter max method
int maxOfTwo = max(3, 7); // Calls the two-parameter version
[Link]("Max of 3 and 7: " + maxOfTwo);
// Demonstrate the use of the three-parameter max method
int maxOfThree = max(4, 9, 2); // Calls the three-parameter version
[Link]("Max of 4, 9, and 2: " + maxOfThree);
Key Points:
Both methods are named max but differ in the number of parameters.
When called, the compiler determines which method to execute based on the arguments
passed.
Example Calls:
int maxOfTwo = max(3, 7); // Calls two-parameter method
int maxOfThree = max(4, 9, 2); // Calls three-parameter method
Output:
9
Alternative Approach
The three-parameter method can reuse the two-parameter method:
static int max(int firstIn, int secondIn, int thirdIn) {
int step1 = max(firstIn, secondIn); // Find max of first two numbers
return max(step1, thirdIn); // Compare with the third number
Concept: This demonstrates calling one method from another.
Polymorphism
Definition: The ability of methods (or operators) with the same name to perform
different functions based on their inputs.
Example: Method overloading is a form of polymorphism.
5.8 Menu-Driven Programs
Definition:
A menu-driven program provides a user with multiple options and processes the selected option
in a structured manner.
Example: Circle Calculations Program
Purpose: Enables the user to calculate and display the area or circumference of a circle
or quit the program.
Structure:
1. Menu Options:
o Enter radius
o Calculate and display area
o Calculate and display circumference
o Quit program
2. Implementation: Use a switch statement within a loop to process user choices.
3. Benefits:
o Each menu option corresponds to a specific method, keeping the program
modular and manageable.
Example: Basic Menu Program
import [Link];
public class MenuDemo {
public static void main(String[] args) {
char response;
Scanner scanner = new Scanner([Link]);
do {
// Display menu
[Link]("\n[1] TIME FOR GROUP A");
[Link]("[2] TIME FOR GROUP B");
[Link]("[3] TIME FOR GROUP C");
[Link]("[4] QUIT PROGRAM");
[Link]("Enter choice [1,2,3,4]: ");
response = [Link]().charAt(0); // Read user input
switch (response) {
case '1':
[Link]("10.00 a.m.");
break;
case '2':
[Link]("1.00 p.m.");
break;
case '3':
[Link]("11.00 a.m.");
break;
case '4':
[Link]("Goodbye!");
break;
default:
[Link]("Invalid option. Please choose 1-4.");
} while (response != '4'); // Repeat until the user chooses to quit
Key Features:
Loop: Keeps displaying the menu until the user selects the "quit" option.
Switch: Processes each menu option based on the user's input.
Default Case: Handles invalid inputs gracefully.
Key Takeaways
Method Overloading simplifies handling similar methods with varying parameters.
Menu-Driven Programs use structured menus and modular methods for better readability
and maintainability.
Polymorphism underpins both concepts, emphasizing reusability and adaptability in code
design.
this keyword in Java
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object.
Usage of Java this keyword
Here is given the 6 usage of java this keyword.
a) this can be used to refer current class instance variable.
b) this can be used to invoke current class method (implicitly)
c) this() can be used to invoke current class constructor.
d) this can be passed as an argument in the method call.
e) this can be passed as argument in the constructor call.
f) this can be used to return the current class instance from the method.
a) this: to refer current class instance variable
The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of ambiguity.
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
............
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we are
using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
void display(){[Link](rollno+" "+name+" "+fee);}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
............
Output:
111 ankit 5000.0
112 sumit 6000.0
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
Program where this keyword is not required
class Student{
int rollno;
String name;
float fee;
Student(int r,String n,float f){
rollno=r;
name=n;
fee=f;
}
void display(){[Link](rollno+" "+name+" "+fee);}
class TestThis3{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}}
............
Output:
111 ankit 5000.0
112 sumit 6000.0
It is better approach to use meaningful names for variables. So we use same name for instance
variables and parameters in real time, and always use this keyword.
2) this: to invoke current class method
You may invoke the method of the current class by using the this keyword. If you don't use the
this keyword, compiler automatically adds this keyword while invoking the method. Let's see the
example
class A{
void m(){[Link]("hello m");}
void n(){
[Link]("hello n");
//m();//same as this.m()
this.m();
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}
............
Output:
hello n
hello m
3) this() : to invoke current class constructor
The this() constructor call can be used to invoke the current class constructor. It is used to reuse
the constructor. In other words, it is used for constructor chaining.
Calling default constructor from parameterized constructor:
class A{
A(){[Link]("hello a");}
A(int x){
this();
[Link](x);
class TestThis5{
public static void main(String args[]){
A a=new A(10);
}}
............
Output:
hello a
10
Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
[Link]("hello a");
A(int x){
[Link](x);
class TestThis6{
public static void main(String args[]){
A a=new A();
}}
............
Output:
hello a
Method Overloading in Java
Method overloading in Java is the feature that enables defining several methods in a class having
the same name but with different parameters lists. These algorithms may vary with regard to the
number or type of parameters. When a method is called, Java decides which version of it to execute
depending on the arguments given. If we have to perform only one operation, having the same
name of the methods increases the readability of the program.
Suppose you have to perform the addition of the given numbers, but there can be any number of
arguments if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior
of the method because its name differs. Here's an explanation with real-life examples:
Math Operations:
In a math class, you might have multiple methods for adding numbers, each accepting a different
number of arguments:
1. public class MathOperations {
2. public int add(int a, int b) {
3. return a + b;
4. }
5. public double add(double a, double b, double c) {
6. return a + b + c;
7. }
8. }
Here, the add method is overloaded to handle both adding two integers and adding three doubles.
String Manipulation:
In a utility class for string manipulation, you might have overloaded methods for concatenating
strings:
1. public class StringUtils {
2. public String concatenate(String str1, String str2) {
3. return str1 + str2;
4. }
5. public String concatenate(String str1, String str2, String str3) {
6. return str1 + str2 + str3;
7. }
8. }
These methods enable concatenating two or three strings together based on the number of
arguments passed.
File Operations:
In a file handling class, you might have overloaded methods for reading files with different
parameters:
1. public class FileManager {
2. public void readFile(String fileName) {
3. // Code to read a file with given name
4. }
5. public void readFile(String fileName, int bufferSize) {
6. // Code to read a file with a given name and buffer size
7. }
8. }
These overloaded methods allow reading files with or without specifying the buffer size.
So, we perform method overloading to figure out the program quickly.
1. Different ways to overload the method
2. By changing the no. of arguments
3. By changing the datatype
4. Why method overloading is not possible by changing the return type
5. Can we overload the main method
6. method overloading with Type Promotion
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In Java, Method Overloading is not possible by changing the return type of the method only.
1) Method Overloading: changing no. of arguments
Method overloading in Java allows defining multiple methods with the same name but different
parameter lists. One common form of overloading is changing the number of arguments in the
method signature. In this example, we have created two methods, the first add() method performs
addition of two numbers, and the second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for calling
methods.
1. // Class Adder contains overloaded methods to add integers
1. class Adder {
2. // Method to add two integers
3. static int add(int a, int b) {
4. return a + b;
5. }
6. // Method to add three integers
7. static int add(int a, int b, int c) {
8. return a + b + c;
9. }
10. }
11. public class TestOverloading1 {
12. public static void main(String[] args) {
13. // Calling the add method with two integers
14. [Link]([Link](11, 11)); // Output: 22
15. // Calling the add method with three integers
16. [Link]([Link](11, 11, 11)); // Output: 33
17. }
18. }
Output:
22
33
2) Method Overloading: changing data type of arguments
Method overloading in Java also allows changing the data type of arguments in the method
signature. Here's an example demonstrating method overloading based on the data type of
arguments: In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double arguments.
1. // Class Adder contains overloaded methods to add numbers
2. class Adder {
3. // Method to add two integers
4. static int add(int a, int b) {
5. return a + b;
6. }
7. // Method to add two doubles
8. static double add(double a, double b) {
9. return a + b;
10. }
11. }
12. public class TestOverloading2 {
13. public static void main(String[] args) {
14. // Calling the add method with two integers
15. [Link]([Link](11, 11)); // Output: 22
16. // Calling the add method with two doubles
17. [Link]([Link](12.3, 12.6)); // Output: 24.9
18. }
19. }
Output:
22
24.9
Q) Why Method Overloading is not possible by changing the return type of method only?
Method overloading in Java is based on the method signature, which includes the method name
and parameter list. The return type alone is not sufficient to distinguish between overloaded
methods because Java does not consider the return type when resolving method calls. If two
methods have the same name and parameter list but different return types, the compiler cannot
determine which method to call based solely on the return type. Let's see how ambiguity may
occur:
1. // Class Adder contains overloaded methods to add numbers
2. class Adder {
3. // Method to add two integers and return an integer
4. static int add(int a, int b) {
5. return a + b;
6. }
7. // Method to add two integers and return a double
8. static double add(int a, int b) {
9. return a + b;
10. }
11. }
12. public class TestOverloading3 {
13. public static void main(String[] args) {
14. // This line of code will cause ambiguity because both add methods have the same signature
15. [Link]([Link](11, 11)); // Error: ambiguity
16. }
17. }
Output:
[Link]: error: method add(int,int) is already defined in class Adder
static double add(int a, int b) {
^
1 error
[Link]([Link](11,11)); //Here, how can java determine which sum() method
should be called?
Note: Compile Time Error is better than Run Time Error. So, java compiler renders
compiler time error if you declare the same method having same parameters.
Can we overload java main() method?
Yes, technically, it is possible to overload the main() method in Java, but it won't be considered as
the entry point for the Java Virtual Machine (JVM) to start the execution of the program. While
overloading the main() method is syntactically valid, it doesn't serve the purpose of being the entry
point for program execution. The JVM expects the standard signature public static void
main(String[] args) for the entry point. Any other overloaded main() method will be treated as a
regular method and won't be invoked by the JVM to start the program. Therefore, although
overloading main() is possible, it's not practically useful for program execution. Let's see a simple
example:
AD
1. // Class TestOverloading4 demonstrates method overloading with different parameter types and
no parameters
2. class TestOverloading4 {
3. public static void main(String[] args) {
4. [Link]("main with String[]");
5. }
6. // Overloaded main method with parameter String args
7. public static void main(String args) {
8. [Link]("main with String");
9. }
10. // Overloaded main method with no parameters
11. public static void main() {
12. [Link]("main without args");
13. }
14. }
Output:
main with String[]
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found. Let's understand the
concept by the figure given below:
As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short datatype can be promoted to int, long, float or double. The char datatype can be promoted to
int,long,float or double and so on.
Example of Method Overloading with Type Promotion if matching found
If there are matching type arguments in the method, type promotion is not performed.
1. class OverloadingCalculation2{
2. void sum(int a,int b){[Link]("int arg method invoked");}
3. void sum(long a,long b){[Link]("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. [Link](20,20);//now int arg sum() method gets invoked
8. }
9. }
Output:
int arg method invoked
Example of Method Overloading with Type Promotion in case of ambiguity
If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.
1. class OverloadingCalculation3{
2. void sum(int a,long b){[Link]("a method invoked");}
3. void sum(long a,int b){[Link]("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. [Link](20,20);//now ambiguity
8. }
9. }
Output:
Compile Time Error
One type is not de-promoted implicitly for example double cannot be depromoted to any type
implicitly.
Advantages of method overloading
Readability and Maintainability: Overloading allows methods to have the same name and different
parameter lists, which increases readability and comprehensibility of the code. It helps developers
to name the different functions in a good way so that other developers can easily understand the
code and maintain it.
Code Reusability: To avoid using too many methods with different names even when their
function is similar, method overloading makes it possible to reuse method names but have different
types or numbers of parameters. It causes the code to be reusable and, therefore, reduces code
duplication.
Flexibility: Method overloading gives the developer an advantage in creating methods which can
be called with any number of different parameters types or numbers. It offers such flexibility to
make APIs that can be expanded to multiple utilities.
Polymorphism: Method overloading is a key to the realization of polymorphism in the Java,
which permits objects of the same type to react differently to method calls depending on the
method's arguments. This behavior somewhat polymorphic, hence leads to modularity and
extensibility of code.
Simplifies API Design: In the case of API design, the method overload is simplifying the interface
as it serves multiple ways in which to interact with the same functionality. The API users can select
the most convenient method signature according to their needs and then create a more thoughtful
and user-centered interface as a result.
Enhances Code Readability: Overloading methods creates an opportunity of having multifaceted
functions encapsulated within a class. Developers not only pick the same method name for similar
operations, but also the purpose of each method becomes clearer, as well as their intended use
cases.
Overriding in Java
Overriding in Java occurs when a subclass implements a method which is already defined in the
superclass or Base Class. The method in the subclass must have the same signature as in the
superclass. It allows the subclass to modify the inherited methods.
Example: Below is an example of how overriding works in Java.
// Example of Overriding in Java
class Animal {
// Base class
void move() { [Link](
"Animal is moving."); }
void eat() { [Link](
"Animal is eating."); }
class Dog extends Animal {
@Override void move()
{ // move method from Base class is overriden in this
// method
[Link]("Dog is running.");
void bark() { [Link]("Dog is barking."); }
public class Kinap {
public static void main(String[] args)
Dog d = new Dog();
[Link](); // Output: Dog is running.
[Link](); // Output: Animal is eating.
[Link](); // Output: Dog is barking.
}
Output
Dog is running.
Animal is eating.
Dog is barking.
Explnation: The Animal class defines base functionalities like move() and eat().t he Dog class
inherits from Animal and overrides the move() method to provide a specific behavior Dog is
running. Both classes can access their own methods. When creating a Dog object, calling
move() executes the overridden method.
Method overriding is a key concept in Java that enables Run-time polymorphism. It allows a
subclass to provide its specific implementation for a method inherited from its parent class. The
actual method executed is determined by the object’s runtime type, not just the reference
variable’s type. This dynamic behaviour is crucial for creating flexible and extensible object-
oriented designs.
Example: Below is the implementation of the Java Method Overriding
// Java program to demonstrate
// method overriding in java
class Parent {
// base class or superclass which is going to overriden
// below
void show() { [Link]("Parent's show()"); }
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
[Link]("Child's show()");
// Driver class
class Kinap {
public static void main(String[] args)
// If a Parent type reference refers
// to a Parent object, then Parent's
// show is called
Parent obj1 = new Parent();
[Link]();
// If a Parent type reference refers
// to a Child object Child's show()
// is called. This is called RUN TIME
// POLYMORPHISM.
Parent obj2 = new Child();
[Link]();
Output
Parent's show()
Child's show()
Explanation: in this code the Child class inherits from the Parent class and overrides the show()
method, providing its own implementation. When a Parent reference points to a Child object, the
Child’s overridden show() method is executed at runtime, showcasing the principle
of polymorphism in Java.
Rules for Java Method Overriding
1. The Overriding and Access Modifiers
An overriding method’s access modifier in a subclass can be more permissive (e.g., protected to
the public) than the overridden method in the superclass. However, reducing the access level
(e.g., making a protected method private) is not allowed and will result in a compile-time error.
Example: Java program to demonstrate Overriding an Access-Modifiers
// A Simple Java program to demonstrate
// Overriding and Access-Modifiers
class Parent {
// private methods are not overridden
private void m1()
[Link]("From parent m1()");
protected void m2()
[Link]("From parent m2()");
class Child extends Parent {
// new m1() method
// unique to Child class
private void m1()
[Link]("From child m1()");
// overriding method
// with more accessibility
@Override public void m2()
[Link]("From child m2()");
class Kinap {
public static void main(String[] args)
// parent class object
Parent P = new Parent();
P.m2();
// child class object
Parent C = new Child();
C.m2();
Output
From parent m2()
From child m2()
Expaination: Here the parent class is overridden by the subclass and from the output we can
easily identify the difference.
2. Override methods can not be overridden
If we don’t want a method to be overridden, we declare it as final. Please see Using Final with
Inheritance.
Example: Java program which shows the final method can not override.
// A Java program to demonstrate that
// final methods cannot be overridden
class Parent {
// Can't be overridden
final void show() {}
class Child extends Parent {
// This would produce error
void show() {}
Output:
3. Static methods can not be overridden(Method Overriding vs Method Hiding)
When you define a static method with the same signature as a static method in the base class, it is
known as method hiding.
Subclass Instance method can override the superclass’s Instance method but when we try to
override the superclass static method gives a compile time error.
Subclass Static Method generate compile time when trying to override superclass Instance
method subclass static method hides when trying to override superclass static method.
Example: Java program to show method hiding in Java.
// Java program to show that
// if the static method is redefined by a derived
// class, then it is not overriding, it is hiding
class Parent {
// Static method in base class
// which will be hidden in subclass
static void m1()
{
[Link]("From parent "
+ "static m1()");
// Non-static method which will
// be overridden in derived class
void m2()
[Link](
"From parent "
+ "non - static(instance) m2() ");
class Child extends Parent {
// This method hides m1() in Parent
static void m1()
[Link]("From child static m1()");
// This method overrides m2() in Parent
@Override public void m2()
{
[Link](
"From child "
+ "non - static(instance) m2() ");
// Driver class
class Kinap {
public static void main(String[] args)
Parent obj1 = new Child();
// here parents m1 called.
// bcs static method can not overriden
obj1.m1();
// Here overriding works
// and Child's m2() is called
obj1.m2();
Output
From parent static m1()
From child non - static(instance) m2()
4. Private methods can not be overridden
Private methods cannot be overridden as they are bonded during compile time. Therefore we
can’t even override private methods in a subclass.
Example: This example shows private method can not be overridden in java
class SuperClass {
private void privateMethod()
[Link](
"it is a private method in SuperClass");
public void publicMethod()
[Link](
"it is a public method in SuperClass");
privateMethod();
class SubClass extends SuperClass {
// This is a new method with the same name as the
// private method in SuperClass
private void privateMethod()
[Link](
"it is private method in SubClass");
// This method overrides the public method in SuperClass
public void publicMethod()
// calls the private method in
// SubClass, not SuperClass
[Link](
"it is a public method in SubClass");
privateMethod();
public class Kinap {
public static void main(String[] args)
SuperClass o1 = new SuperClass();
// calls the public method in
// SuperClass
[Link]();
SubClass o2 = new SubClass();
// calls the overridden public
// method in SubClass
[Link]();
Output
it is a public method in SuperClass
it is a private method in SuperClass
it is a public method in SubClass
it is private method in SubClass
5. Method must have the same return type (or subtype)
From Java 5.0 onwards it is possible to have different return types for an overriding method in
the child class, but the child’s return type should be a sub-type of the parent’s return type. This
phenomenon is known as the covariant return type.
Example: Java Program which shows Covariant Return Type in Method Overriding.
class SuperClass {
public Object method()
{
[Link](
"This is the method in SuperClass");
return new Object();
class SubClass extends SuperClass {
public String method()
[Link](
"This is the method in SubClass");
return "Hello, World!";
// having the Covariant return type
public class Kinap {
public static void main(String[] args)
SuperClass obj1 = new SuperClass();
[Link]();
SubClass obj2 = new SubClass();
[Link]();
Output
This is the method in SuperClass
This is the method in SubClass
6. showsInvoking overridden method from sub-class
We can call the parent class method in the overriding method using the super keyword.
Example: This example shows we can parent’s overridden method using super an.
// A Java program to demonstrate that overridden
// method can be called from sub-class
// Base Class
class Parent {
void show() { [Link]("Parent's show()"); }
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
[Link]();
[Link]("Child's show()");
// Driver class
class Kinap{
public static void main(String[] args)
Parent o = new Child();
[Link]();
Output
Parent's show()
Child's show()
Overriding and Constructor
We can not override the constructor as the parent and child class can never have a constructor
with the same name(The constructor name must always be the same as the Class name).
Overriding and Exception-Handling
Below are two rules to note when overriding methods related to exception handling.
Rule 1:
If the super-class overridden method does not throw an exception, the subclass overriding
method can only throw the unchecked exception, throwing a checked exception will lead to a
compile-time error.
Example: Below is an example of a java program when the parent class method does not declare
the exception
// Java program to demonstrate overriding when
// superclass method does not declare an exception
class Parent {
void m1() { [Link]("From parent m1()"); }
void m2() { [Link]("From parent m2()"); }
class Child extends Parent {
@Override
// no issue while throwing unchecked exception
void m1() throws ArithmeticException
[Link]("From child m1()");
}
@Override
// compile-time error
// issue while throwing checked exception
void m2() throws Exception
[Link]("From child m2");
Output
Explanation: this example shows that uper-class overridden method does not throw an
exception, the subclass overriding method can only throw the exception because the super class
does not declare the exception.
Rule 2.
If the superclass overridden method does throw an exception, the subclass overriding method can
only throw the same, subclass exception. Throwing parent exceptions in the Exception
hierarchy will lead to compile time error. Also, there is no issue if the subclass overridden
method does not throw any exception.
Example: Java program to demonstrate overriding when superclass method does declare an
exception
class Parent {
void m1() throws RuntimeException
[Link]("From parent m1()");
class Child1 extends Parent {
@Override void m1() throws RuntimeException
[Link]("From child1 m1()");
class Child2 extends Parent {
@Override void m1() throws ArithmeticException
[Link]("From child2 m1()");
}
}
class Child3 extends Parent {
@Override void m1()
[Link]("From child3 m1()");
class Child4 extends Parent {
@Override void m1() throws Exception
// This will cause a compile-time error due to the
// parent class method not declaring Exception
[Link]("From child4 m1()");
public class MethodOverridingExample {
public static void main(String[] args)
Parent p1 = new Child1();
Parent p2 = new Child2();
Parent p3 = new Child3();
Parent p4 = new Child4();
// Handling runtime exceptions for each child class
// method
try {
p1.m1();
catch (RuntimeException e) {
[Link]("Exception caught: " + e);
try {
p2.m1();
catch (RuntimeException e) {
[Link]("Exception caught: " + e);
try {
p3.m1();
catch (Exception e) {
[Link]("Exception caught: " + e);
// Child4 throws a compile-time error due to
// mismatched exception type
try {
p4.m1(); // This will throw a compile-time error
catch (Exception e) {
[Link]("Exception caught: " + e);
Output
Overriding and Abstract Method
Abstract methods in an interface or abstract class are meant to be overridden in derived concrete
classes otherwise a compile-time error will be thrown.
Overriding and Synchronized/strictfp Method
The presence of a synchronized/strictfp modifier with the method has no effect on the rules of
overriding, i.e. it’s possible that a synchronized/strictfp method can override a non-
synchronized/strictfp one and vice-versa.
// A Java program to demonstrate
// multi-level overriding
// Base Class
class Parent {
void show() { [Link]("Parent's show()"); }
// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
void show() { [Link]("Child's show()"); }
// Inherited class
class GrandChild extends Child {
// This method overrides show() of Parent
void show()
[Link]("GrandChild's show()");
// Driver class
class Kinap {
public static void main(String[] args)
Parent o = new GrandChild();
[Link]();
Output
GrandChild's show()
Method Overriding vs Method Overloading
1. Overloading is about the same method having different signatures. Overriding is about the
same method, and same signature but different classes connected through inheritance.
2. Overloading is an example of compiler-time polymorphism and overriding is an example of
run-time polymorphism.
Method Overriding In Java-FAQs
Q1. What is Method Overriding?
Overridden methods enable Java’s run-time polymorphism, allowing subclasses to provide
specific implementations of methods defined in a parent class. This supports the “one interface,
multiple methods” concept of polymorphism. Dynamic Method Dispatch is a key feature,
enabling code libraries to call methods on new class instances without recompiling, while
maintaining a clean, abstract interface. It allows calling methods from derived classes without
knowing their specific type.
Q2. When to apply Method Overriding? (with example)
Overriding and inheritance work together to apply polymorphism by organizing superclasses
and subclasses in a hierarchy, from general to specialized. The superclass provides common
methods for subclasses to use or override, ensuring flexibility while maintaining a consistent
interface. For example, in an employee management system, the base class Employee defines
methods like raiseSalary(), transfer(), and promote(). Subclasses such as Manager or Engineer
can override these methods with their own logic. This allows us to pass a list of employees, call
methods like raiseSalary(), and let each employee type execute its own implementation without
knowing the specific type of employee.
// Java program to demonstrate application
// of overriding in Java
// Base Class
class Employee {
public static int base = 10000;
int salary() { return base; }
// Inherited class
class Manager extends Employee {
// This method overrides salary() of Parent
int salary() { return base + 20000; }
// Inherited class
class Clerk extends Employee {
// This method overrides salary() of Parent
int salary() { return base + 10000; }
// Driver class
class Main {
// This method can be used to print the salary of
// any type of employee using base class reference
static void printSalary(Employee e)
{
[Link]([Link]());
public static void main(String[] args)
Employee obj1 = new Manager();
// We could also get type of employee using
// one more overridden [Link] getType()
[Link]("Manager's salary : ");
printSalary(obj1);
Employee obj2 = new Clerk();
[Link]("Clerk's salary : ");
printSalary(obj2);
Output
Manager's salary : 30000
Clerk's salary : 20000