Method overloading

461 views
310 views

Published on

Method Overloading

Published in: Education, Technology, Business
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
461
On SlideShare
0
From Embeds
0
Number of Embeds
10
Actions
Shares
0
Downloads
19
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Method overloading

  1. 1. BY: HUMA SAMIN Method Overloading
  2. 2. Method Overloading In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. The methods are called overloaded methods. The process is called method overloading. When an overloaded method is invoked, Java uses the type and/or number of arguments t0 determine which version of the overloaded method to actually call.
  3. 3. Example public Class OverLoadDemo { void test( ) { System.out.println(“No parameters”); } void test(int a) { System.out.println(“a: ”+a); } void test( int a, int b) { System.out.println(“a: ”+ a+ “b: ”+ b); } double test(double a) { System.out.println(“a: ”+ a); return a*a; } }
  4. 4. Example cont.. public class OverLoadDemoDriver { public static void main(String args[]) { OverLoadDemo o=new OverLoadDemo( ); o.test( ); o.test(10); o.test(10,20); double d; d=o.test( 10.7); } } Note: 1. Method overloading doesn’t depend on the return type. 2. Automatic type casting is allowed while calling methods.
  5. 5. Method Overloading Method overloading implements the concept of polymorphism in java. “Poly” means many and “morph” means forms.
  6. 6. Constructor Overloading Just like methods constructors can be overloaded. One class can have more than one constructors defined. All the rules of constructor overloading are the same as that of method overloading.
  7. 7. Example public class Student { //data members or instance variables private int rollNo; public int semester; //behavior or methods are kept public // Overloaded Constructors public Student( ) { rollNo=10; semester=2; } public Student(int r) { rollNo=r; semester=2; } public Student(int r, int s) { rollNo=r; semester=s; } public void displayValues( ) { System.out.println(rollNo); System.out.println(semester); } }
  8. 8. Example cont.. public class StudentDriver { public static void main(String args[ ]) { Student s, s1,s2; s=new Student( ); s1=new Student(23); s2=new Student(45,3); s.displayValues(); s1.displayValues(); s2.displayValues(); } }

×