Overloaded methods allows to reuse the same method name in a class, but having different signature. Signature means one method varies with other method in terms of below points:
- Number of arguments.
- Types of arguments.
- Order of arguments.
There are some rules as below:
- Overloaded methods must change the argument list.
- Overloaded methods can change the return type.
- Overloaded methods can be overloaded in the same class or subclass.
- Overloaded methods can declare new or broaded checked exception.
Overloaded methods can change the access modifier.
1 2 3 4 5 6 7 8 9 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 |
package technical.jungle.com.overloading; public class Shape { public Shape(){ System.out.println("www.Technicaljungle.com -> Shape()"); } public Shape(int value){ System.out.println("Shape(int value) -> value : " + value); } public Shape(int v1, float v2){ System.out.println("Shape(int v1,float v2)->v1: " + v1 + "-> v2: " + v2); } public Shape(float value){ System.out.println("Shape(float value) -> value : " + value); } public static void main(String[] args) { Shape shape1 = new Shape(2f); Shape shape2 = new Shape(100, 102f); Shape shape3 = new Shape(); Shape shape4 = new Shape(200); } } Output: Shape(float value) -> value : 2.0 Shape(int v1,float v2)->v1: 100-> v2: 102.0 www.Technicaljungle.com -> Shape() Shape(int value) -> value : 200 |
Some key points for above demo
- Shape class is having all constructors which different signatures.
- From main method different parameters has been passed and object has been created with different initializations.
1 2 3 4 5 6 7 8 9 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 |
package technical.jungle.com.overloading; public class ShapeOverload { public void Shape(){ System.out.println("www.Technicaljungle.com -> Shape()"); } public void Shape(int value){ System.out.println("Shape(int value) -> value : " + value); } public void Shape(int v1, float v2){ System.out.println("Shape(int v1,float v2)->v1: " + v1 + "-> v2: " + v2); } public void Shape(float value){ System.out.println("Shape(float value) -> value : " + value); } public static void main(String[] args) { ShapeOverload obj = new ShapeOverload(); obj.Shape(100, 102f); obj.Shape(); obj.Shape(200); obj.Shape(); } } Shape(int v1,float v2)->v1: 100-> v2: 102.0 www.Technicaljungle.com -> Shape() Shape(int value) -> value : 200 www.Technicaljungle.com -> Shape() |
Some key points for above demo
- ShapeOverload class is having methods, named Shape, with signatures.
- In main method object is getting created and with Shape method is getting called with different parameters.
If you like the post then please socialize it. Happy Sharing. Loudly Subscribing.