+ 22

Overloading vs overriding

I heared both are concepts of polymorphism . overloading is compile time polymorphism and overriding is run-time . I need a brief explanation with real time example Thank you !!

3rd May 2017, 7:04 PM
Prudhvi Raaj
Prudhvi Raaj - avatar
3 ответов
+ 6
Overriding is when a subclass takes a method of its parent class and overrides it so that the output of that method will be different from its initial output. Example (Overriding): Class Parent using_Mouth(){ print "You will do your homework" } //Outputs You will do your homework Class Child Extend Parent using_Mouth(){ print "I will not do my homework" } //Outputs I will not do my homework -Above the intial output of the method is the top one but then the subclass overrides it to give a different output but using the same method. -The syntax is obviously not correct but it's simplified so that you can understand Overloading is when you need a method to do the same functionality but with different parameters. Example (Overloading): int calculate_ADD(int var1, int var2){ return var1 + var2 } //Outputs the sum of two integers double calculate_ADD(double var1, double var2){ return var1 + var2 } //Outputs the sum of two doubles -Above the method just has the function to add two variables together and that's why it's a perfect candidate for Overloading because you can then simply switch the data types and you'd get the same functionality, the sum of two variables -Again, not correct syntax but hopefully you'll understand better
3rd May 2017, 7:28 PM
Ghauth Christians
Ghauth Christians - avatar
3rd May 2017, 7:17 PM
Tashi N
Tashi N - avatar
+ 7
Overload when the methods had same name and retun type but different argument list. Override when a subclass override the method of superclass or interface annotate with @override. Example: Overload: String greetings(){ System.out.println("Hello World!"); } String greetings(String name){ System.out.println("Hello "+name+"!"); } Override: class A{ String greetings(){ System.out.println("Hello world!"); } } class B extends A{ @Override String greetings(){ System.out.println("Hi there!"); } }
3rd May 2017, 7:22 PM
Szabó Gábor
Szabó Gábor - avatar