7 Overloading Methods — Java Programming
7.1 Introduction
In this chapter you will learn more about the capabilities of methods in Java and will extend your skills at building and using objects and classes. The main objective of this chapter is to consider overloading in which multiple methods in the same class can have the same name. You will also learn about overloading constructors, the concepts of early binding and late bindings, and a few more miscellaneous concepts like passing objects as parameters, accessor, mutator method etc.
7.2 Method overloading
Method Overloading means a function can be called with different number of and types of parameters with the same method name. Method overloading is one of the ways through which Java implements polymorphism. Usually, when we call a method, we call the same method with a few arguments or more number of arguments, that is, varying number of parameters, and varying types of parameters. Thus is done by overloading the methods. For function overloading many methods with same name but different arguments are created.
For example:
static void profit(int x, int y); static void profit(double d); static void profit(int x, float f);
Program 7.1 Program to demonstrate function overloading with varying number of arguments (parameters).
//overloadDemo.java //Program to demonstrate method (function overload) //click here for code class overload { void ex() { System.out.println("no parameters"); } void ex(int a) { System.out.println("one parameter: " +a); } void ex(int a,int b) { System.out.println("two parameter: " +a+" "+b); } double ex(double a) { System.out.println("double parameters: "+a); return(a); } } class overloadDemo { public static void main(String args[]) { overload ovrload=new overload(); double result; ovrload.ex(); ovrload.ex(1); ovrload.ex(1,2); result=ovrload.ex(1.52); System.out.println(result); } } /* Output: no parameters one parameter: 1 two parameter: 1 2 double parameters: 1.52 1.52 */
Program 7.2 Another Program to demonstrate function overloading with different types of arguments (parameters).
//overloadTypes.java //click here for code import java.io.*; public class overloadTypes { public void show(int a) { System.out.println("integer a="+a); } public void show(int a,int b) { System.out.println("integer a="+a+" integer b="+b); } public void show(double a) { System.out.println("double a="+a); } public void show(double a,double b) { System.out.println("double a="+a+" and double b="+b); } public void show(String a) { System.out.println("String a="+a); } public void show(String a,String b) { System.out.println("String a="+a+" and "+"String b="+b); } public static void main(String args[]) { int x=10,y=20; overloadTypes ov=new overloadTypes(); ov.show(x); ov.show(x,y); double a=123.456,b=0.123456; ov.show(a); ov.show(a,b); String s1="cse",s2="it"; ov.show(s1); ov.show(s1,s2); } } /* Output: integer a=10 integer a=10 integer b=20 double a=123.456 double a=123.456 and double b=0.123456 String a=cse String a=cse and String b=it */
When an overload method is called, java looks for a match between arguments used to call the method and the method’s parameters. But this match is not compulsory, Java automatically will resolve the complications.
Program 7.3 Program to demonstrate polymorphism in Java
//shapeDemo.java //click here for code class shape{ void draw(){} void erase(){} } class circle extends shape{ void draw(){ System.out.println("draw circle"); } void erase(){ System.out.println("erase circle"); } } class square extends shape{ void draw(){ System.out.println("draw square"); } void erase(){ System.out.println("erase square"); } } class triangle extends shape{ void draw(){ System.out.println("draw triangle"); } void erase(){ System.out.println("erase triangle"); } } class rectangle extends shape{ void draw(){ System.out.println("draw rectangle"); } void erase(){ System.out.println("erase rectangle"); } } class shapeDemo{ public static void main(String args[]) { triangle t =new triangle(); t.draw(); circle c = new circle(); c.draw(); rectangle r = new rectangle(); r.draw(); } } /* Output: draw triangle draw circle draw rectangle */
7.3 Binding
Connecting a method call to a method body is called binding. When binding is performed before the program is run(by the complier and linker, if there is one), it is called early binding. C compilers have only one kind of method call and that is early binding. Late binding means that binding occurs at runtime based on the type of object. Late binding is also called as dynamic binding or runtime binding. When a language implements late binding, there must be some mechanism to determine the type of the object at runtime and to call the appropriate method. That is, the compiler still does not know the object type, but the method call mechanism finds out and calls the correct method body. The late binding mechanism varies from language to language, but you can imagine that some sort of type information must be installed in the objects.
All method binding in Java is late binding unless a method has been declared as final.
We can also overload constructors. The combination of the method name and the parameter list is called the method signature.
Variables defined inside a method body are only visible to that method and cannot be accessed outside the method.
7.4 Using object as parameters
We can pass objects as parameters to methods. One of the uses of object parameters involves constructors.
** Variables are passed to a method by call by value. Objects are passed by use of call by reference.
Program 7.4 Program to pass objects to methods.
//passObj.java //click here for code class test{ int a,b; test(int i,int j){ a=i; b=j; } boolean equals(test ob){ //equals() is a method that compares two objects and returns true if they are equal or else // false. if(ob.a==a&&ob.b==b) return true; else return false; } } class passObj{ public static void main(String args[]){ test ob1=new test(100,22); test ob2=new test(100,22); test ob3=new test(-1,-1); System.out.println("ob1==ob2:"+ob1.equals(ob2)); System.out.println("ob1==ob3:"+ob1.equals(ob3)); } } /* Output: ob1==ob2:true ob1==ob3:false */
7.5 Returning objects
Objects can be returned by
Return objectname;
7.6 The class methods and instance methods
7.6.1 Instance methods
We define methods in classes. In order to use the methods we need to first create objects of the classes. We then make a call using the following statement.
Objectname.methodname();
This is an instance method.
7.6.2 Class methods
We create class methods to allow us to call a method without creating an instance of the class. Therefore class methods are available to all the classes.
We call them by naming the class and not the object.
class.methodname();
But to declare a method as a class method we use the keyword static. Class methods do not require objects of a class. Class methods are useful for creating methods which you want to be universally available.
Program 7.5 Demonstration of class method. //classMethod.java //Click here for code class xyz{ public static void xyzmethod() { System.out.println("in xyz method"); } } public class classMethod{ public static void main(String args[]) { //calling class method. xyz.xyzmethod(); } } /* Output: in xyz method */
7.7 Overloading constructors
Constructor’s can be overloaded too. Consider the following example.
Program 7.6 Program to add, subtract and multiply complex numbers. This program adds, subtracts, and multiplies complex numbers
//Program 7.6 Program to demonstrate constructor overloading. //complex.java //Click here for code import java.io.*; public class complex{ float re,im; public complex() { re=0;im=0; } public complex(float x, float y) { re=x; im=y; } public complex(complex ob) { re=ob.re; im=ob.im; } public void getnum() { Float fre=0f; Float fin=0f; try { DataInputStream in; in=new DataInputStream(System.in); System.out.println("enter the complex number"); String s=in.readLine(); fre=Float.parseFloat(s); s=in.readLine(); fin=Float.parseFloat(s); re=fre; im=fin; //re=fre.FloatValue(); //im=fin.FloatValue(); } catch(Exception e) { System.out.println("I/O error"+e); System.exit(1); } } public complex add(complex ob) { complex c =new complex(); c.re=re+ob.re; c.im=im+ob.im; return c; } public complex sub(complex ob) { complex c =new complex(); c.re=re-ob.re; c.im=im-ob.im; return c; } public complex mul(complex ob) { complex c =new complex(); c.re=re*ob.re-im*ob.im; c.im=im*ob.im+im*ob.re; return c; } public void show() { if(im>0) System.out.println(re+"+j"+im); else if(im<0) { float t=-1*im; System.out.println(re+"-j"+t); } else if(im==0) System.out.println(re); } public static void main(String args[]) { complex a = new complex(); complex b = new complex(); complex c = new complex(); complex d = new complex(); complex e = new complex(); a.getnum(); b.getnum(); c=a.add(b); d=a.sub(b); e=a.mul(b); c.show(); d.show(); e.show(); } } /* Output: enter the complex number 2.3 1.2 enter the complex number 4.2 3.2 6.5+j4.4 -1.8999999-j2.0 5.8199987+j8.88 */
7.8 Accessor and Mutator methods
Accessor methods are those that access only instance variables and don’t alter them. Mutation methods are the ones that change instance variables.
For example, consider class java.util.date. This class Date may contain many methods to get month, date or year etc.
| Accessor Methods | Mutator Methods |
| int getDate() | void setDate() |
| int getMonth() | void setMonth() |
| int getYear() | void setYear() |
A mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter, which returns the value of the private member variable. They are also known collectively as accessors. [7.1]
The mutator method is most often used in object-oriented programming, in keeping with the principle of encapsulation. According to this principle, member variables of a class are made private to hide and protect them from other code, and can only be modified by a public member function (the mutator method), which takes the desired new value as a parameter, optionally validates it, and modifies the private member variable. Mutator methods can be compared to assignment operator overloading but they typically appear at different levels of the object hierarchy.
In this example of a simple class representing a student with only the name stored, one can see the variable name is private, i.e. only visible from the Student class, and the “setter” and “getter” are public, namely the “getName()
” and “setName(name)
” methods.
public class Student { private String name; public String getName() { //getter or accessor return name; } public void setName(String newName) { //setter or mutator name = newName; } }
7.9 Recursion
Java supports recursion. A method calling itself is called recursive method.
Program 7.7. Program to calculate factorial using recursion.
//recursionFactorial.java //Click here for code class fact{ int fact(int n){ int result; if(n==1)return 1; result=fact(n-1)*n; return result; } } class recursionFactorial{ public static void main(String args[]) { fact f = new fact(); System.out.println("factorial of 3 is "+f.fact(3)); } } /* Output: factorial of 3 is 6 */
Program 7.8 Program to solve towers of Hanoi problems using recursion.
//recursionHanoi.java //Click here for code class recursionHanoi{ public static void main(String args[]){ int nvalue=3; //number of disks char snvalue='L', invalue='C',dnvalue='R'; recursionHanoi towers; towers=new recursionHanoi(); towers.hanoi(nvalue,snvalue,invalue,dnvalue); } void hanoi(int n, char sndl, char indl, char dndl) { if(n!=0) { //move n-1 disks from staring to intermediate peg hanoi(n-1,sndl,dndl,indl); //move disk n from start to destination peg System.out.println("move disk "+n+" from "+ sndl+" to "+dndl); //move n-1 disks from intermediate to destination needle hanoi(n-1,indl,sndl,dndl); } } } /* Output: move disk 1 from L to R move disk 2 from L to C move disk 1 from R to C move disk 3 from L to R move disk 1 from C to L move disk 2 from C to R move disk 1 from L to R */
7.10 Using command line arguments
This is again similar to C.
Program 7.9 Program to print the command line arguments. //cmdline.java //Click here for code class cmdline{ public static void main(String args[]){ for(int i=0; i<args.length;i++) System.out.println("args["+i+":"+args[i]); } } /* >cmdLine hello hello
All the command line arguments are passed as strings. We must convert numeric values to actual numbers from string function.
7.11 Summary
In this chapter you have learned so far, more details classes and objects, overloading methods and constructors. You were given a brief overview of recursion and command line arguments.