Java Overloading Methods

With this example we are going to demonstrate how to use Overloading Java Methods in a class. Overloaded methods are methods with the same name signature but either a different number of parameters or different types in the parameter list. We have created a class, that has constructors and methods with the same names but with different arguments and use them in new class instances to see their behavour. Specificaly:

Let’s take a look at the code snippet that follows:  

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.javacodegeeks.snippets.core;
 
 
class Tree {
 
    int treeHeight;
 
    Tree() {
 
  System.out.println("Plant a seedling");
 
  treeHeight = 0;
    }
 
    //Overloaded Constructor
    //Notice that the two constructors have the same name , but different arguments
    Tree(int num) {
 
  System.out.println("Creating new Tree that is " + num + " meters tall");
 
  treeHeight = num;
    }
 
    void info() {
 
  System.out.println("Tree is " + treeHeight + " meters tall");
    }
 
    void info(String str) {
 
  System.out.println(str + ": Tree is " + treeHeight + " meters tall");
    }
}
 
public class  MethodOverloading{
 
    public static void main(String[] args) {
 
   
 
  for (int i = 0; i < 2; i++) {
 
 
Tree t = new Tree(i);
 
 
t.info();
 
 
t.info("overloaded method");
 
  }
 
  // Overloaded constructor:
 
  new Tree();
 
    }
}
Output
Creating new Tree that is 0 meters tall
Tree is 0 meters tall
overloaded method: Tree is 0 meters tall
Creating new Tree that is 1 meters tall
Tree is 1 meters tall
overloaded method: Tree is 1 meters tall
Plant a seedling

 This was an example of how to use overloaded methods in a class in Java.

Exit mobile version