SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Method Overloading
in
Java
• If a class has multiple methods having same
name but different in parameters, it is known
as Method Overloading.
• Suppose you have to perform addition of the
given numbers but there can be any number
of arguments, if you write the method such as
a( int, int) for two parameters, and b(int, int
,int) for three parameters then it may be
difficult for you as well as other programmers
to understand the behavior of the method
because its name differs.
• So, we perform method overloading to figure
out the program quickly.
Advantage of method overloading
• Method overloading increases the readability
of the program.
Different ways to overload the method
• By changing number of arguments
• By changing the data type
Method Overloading: changing no. of
arguments
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static int add(int a, int b, int c)
{
return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
• we have created two methods, first add()
method performs addition of two numbers
and second add method performs addition of
three numbers.
Method Overloading: changing data
type of arguments
• class Adder
• {
• static int add(int a, int b)
• {return a+b;}
• static double add(double a, double b)
• {return a+b;}
• }
• class TestOverloading2
• {
• public static void main(String[] args)
• {
• System.out.println(Adder.add(11,11));
• System.out.println(Adder.add(12.3,12.6));
• }
• }
• we have created two methods that differs in
data type. The first add method receives two
integer arguments and second add method
receives two double arguments.
Why Method Overloading is not possible by
changing the return type of method only?
In java, method overloading is not possible by
changing the return type of the method only
because of ambiguity. Let's see how ambiguity
may occur:
• class Adder
• {
• static int add(int a,int b){return a+b;}
• static double add(int a,int b){return a+b;}
• }
• class TestOverloading3{
• public static void main(String[] args){
• System.out.println(Adder.add(11,11));//ambig
uity
• }}
Compile Time Error: method add(int, int) is
already defined in class Adder
System.out.println(Adder.add(11,11)); //Here,
how can java determine which sum() method
should be called?
Can we overload java main() method?
• Yes, by method overloading. You can have any
number of main methods in a class by method
overloading. But JVM calls main() method
which receives string array as arguments only.
Let's see the simple example:
class TestOverloading4
{
public static void main(String[] args)
{System.out.println("main with String[]");}
public static void main(String args)
{System.out.println("main with String");}
public static void main()
{System.out.println("main without args");}
}
Method Overriding in Java
• If subclass (child class) has the same method
as declared in the parent class, it is known
as method overriding in java.
• In other words, If subclass provides the
specific implementation of the method that
has been provided by one of its parent class, it
is known as method overriding.
Usage of Java Method Overriding
• Method overriding is used to provide specific
implementation of a method that is already
provided by its super class.
• Method overriding is used for runtime
polymorphism
Rules for Java Method Overriding
• method must have same name as in the
parent class
• method must have same parameter as in the
parent class.
• must be IS-A relationship (inheritance).
Understanding the problem without
method overriding
• class Vehicle{
• void run(){System.out.println("Vehicle is runn
ing");} }
• class Bike extends Vehicle{
• public static void main(String args[]){
• Bike obj = new Bike();
• obj.run();
• } }
Example of method overriding
• class Vehicle{
• void run(){System.out.println("Vehicle is running");} }
• class Bike2 extends Vehicle{
• void run(){System.out.println("Bike is running safely");}
• public static void main(String args[]){
• Bike2 obj = new Bike2();
• obj.run();
• }
super keyword in java
• The super keyword in java is a reference
variable which is used to refer immediate
parent class object.
Usage of java super Keyword
• super can be used to refer immediate parent
class instance variable.
• super can be used to invoke immediate parent
class method.
• super() can be used to invoke immediate
parent class constructor.
super is used to refer immediate parent
class instance variable.
• We can use super keyword to access the data
member or field of parent class. It is used if parent
class and child class have same fields.
• lass Animal{
• String color="white";
• }
• class Dog extends Animal{
• String color="black";
• void printColor(){
• System.out.println(color);//prints color of Dog
class
• System.out.println(super.color);//prints color
of Animal class
• } }
• class TestSuper1
• {
• public static void main(String args[])
• {
• Dog d=new Dog();
• d.printColor();
• }}
super can be used to invoke parent
class method
• The super keyword can also be used to invoke
parent class method. It should be used if
subclass contains the same method as parent
class. In other words, it is used if method is
overridden.
• class Animal{
• void eat(){System.out.println("eating...");}
• }
• class Dog extends Animal{
• void eat(){System.out.println("eating bread...");}
• void bark(){System.out.println("barking...");}
• void work(){
• super.eat();
• bark();
• } }
• class TestSuper2
• {
• public static void main(String args[])
• {
• Dog d=new Dog();
• d.work();
• }
• }
super is used to invoke parent class
constructor.
• class Animal{
• Animal(){System.out.println("animal is created");}
• }
• class Dog extends Animal{
• Dog(){
• super();
• System.out.println("dog is created");
• }
• }
• class TestSuper3
• {
• public static void main(String args[])
• {
• Dog d=new Dog();
• }
• }
Method overloading

Weitere ähnliche Inhalte

Was ist angesagt?

Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentationkunal kishore
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloadinggarishma bhatia
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Type casting in java
Type casting in javaType casting in java
Type casting in javaFarooq Baloch
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++HalaiHansaika
 
Java package
Java packageJava package
Java packageCS_GDRCST
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Michelle Anne Meralpis
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++Vineeta Garg
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C ProgrammingShuvongkor Barman
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member FunctionsMOHIT AGARWAL
 

Was ist angesagt? (20)

Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
OOP java
OOP javaOOP java
OOP java
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Applets
AppletsApplets
Applets
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
classes and objects in C++
classes and objects in C++classes and objects in C++
classes and objects in C++
 
Java package
Java packageJava package
Java package
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Constructors and Destructors
Constructors and DestructorsConstructors and Destructors
Constructors and Destructors
 
Inheritance in c++
Inheritance in c++Inheritance in c++
Inheritance in c++
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Data types in java
Data types in javaData types in java
Data types in java
 
Static Data Members and Member Functions
Static Data Members and Member FunctionsStatic Data Members and Member Functions
Static Data Members and Member Functions
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 

Andere mochten auch (20)

Data structures
Data structuresData structures
Data structures
 
Circular queue
Circular queueCircular queue
Circular queue
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Stacks in Data Structure
Stacks in Data StructureStacks in Data Structure
Stacks in Data Structure
 
Java naming conventions
Java naming conventionsJava naming conventions
Java naming conventions
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
single linked list
single linked listsingle linked list
single linked list
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
linked list
linked listlinked list
linked list
 
L6 structure
L6 structureL6 structure
L6 structure
 
01 05 - introduction xml
01  05 - introduction xml01  05 - introduction xml
01 05 - introduction xml
 
Introduction to data structure by anil dutt
Introduction to data structure by anil duttIntroduction to data structure by anil dutt
Introduction to data structure by anil dutt
 
Data structure lecture 1
Data structure lecture 1Data structure lecture 1
Data structure lecture 1
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
5 Array List, data structure course
5 Array List, data structure course5 Array List, data structure course
5 Array List, data structure course
 
3 Array operations
3   Array operations3   Array operations
3 Array operations
 
Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)Data Structure (Introduction to Data Structure)
Data Structure (Introduction to Data Structure)
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
 
Trees data structure
Trees data structureTrees data structure
Trees data structure
 

Ähnlich wie Method overloading

Ähnlich wie Method overloading (20)

Overloadingmethod
OverloadingmethodOverloadingmethod
Overloadingmethod
 
Super Keyword in Java.pptx
Super Keyword in Java.pptxSuper Keyword in Java.pptx
Super Keyword in Java.pptx
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
UNIT_-II_2021R.pptx
UNIT_-II_2021R.pptxUNIT_-II_2021R.pptx
UNIT_-II_2021R.pptx
 
Java - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptxJava - Inheritance_multiple_inheritance.pptx
Java - Inheritance_multiple_inheritance.pptx
 
C#2
C#2C#2
C#2
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
chapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptxchapter 1-overview of java programming.pptx
chapter 1-overview of java programming.pptx
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
 
BCA Oveloading and Overriding (2).pptx
BCA Oveloading and Overriding (2).pptxBCA Oveloading and Overriding (2).pptx
BCA Oveloading and Overriding (2).pptx
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java introduction
Java introductionJava introduction
Java introduction
 

Mehr von Lovely Professional University

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageLovely Professional University
 

Mehr von Lovely Professional University (20)

The HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup languageThe HyperText Markup Language or HTML is the standard markup language
The HyperText Markup Language or HTML is the standard markup language
 
Working with JSON
Working with JSONWorking with JSON
Working with JSON
 
Yargs Module
Yargs ModuleYargs Module
Yargs Module
 
NODEMON Module
NODEMON ModuleNODEMON Module
NODEMON Module
 
Getting Input from User
Getting Input from UserGetting Input from User
Getting Input from User
 
fs Module.pptx
fs Module.pptxfs Module.pptx
fs Module.pptx
 
Transaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptxTransaction Processing in DBMS.pptx
Transaction Processing in DBMS.pptx
 
web_server_browser.ppt
web_server_browser.pptweb_server_browser.ppt
web_server_browser.ppt
 
Web Server.pptx
Web Server.pptxWeb Server.pptx
Web Server.pptx
 
Number System.pptx
Number System.pptxNumber System.pptx
Number System.pptx
 
Programming Language.ppt
Programming Language.pptProgramming Language.ppt
Programming Language.ppt
 
Information System.pptx
Information System.pptxInformation System.pptx
Information System.pptx
 
Applications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptxApplications of Computer Science in Pharmacy-1.pptx
Applications of Computer Science in Pharmacy-1.pptx
 
Application of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptxApplication of Computers in Pharmacy.pptx
Application of Computers in Pharmacy.pptx
 
Deploying your app.pptx
Deploying your app.pptxDeploying your app.pptx
Deploying your app.pptx
 
Setting up github and ssh keys.ppt
Setting up github and ssh keys.pptSetting up github and ssh keys.ppt
Setting up github and ssh keys.ppt
 
Adding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.pptAdding a New Feature and Deploying.ppt
Adding a New Feature and Deploying.ppt
 
Requiring your own files.pptx
Requiring your own files.pptxRequiring your own files.pptx
Requiring your own files.pptx
 
Unit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptxUnit-2 Getting Input from User.pptx
Unit-2 Getting Input from User.pptx
 
Yargs Module.pptx
Yargs Module.pptxYargs Module.pptx
Yargs Module.pptx
 

Kürzlich hochgeladen

solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging systemgokuldongala
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchrohitcse52
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....santhyamuthu1
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Akarthi keyan
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Sean Meyn
 
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...amrabdallah9
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfJulia Kaye
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfodunowoeminence2019
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingMarian Marinov
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesDIPIKA83
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical SensorTanvir Moin
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabusViolet Violet
 
Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfGiovanaGhasary1
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxYogeshKumarKJMIT
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxHome
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptxMUKULKUMAR210
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfNaveenVerma126
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technologyabdulkadirmukarram03
 

Kürzlich hochgeladen (20)

solar wireless electric vechicle charging system
solar wireless electric vechicle charging systemsolar wireless electric vechicle charging system
solar wireless electric vechicle charging system
 
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai searchChatGPT-and-Generative-AI-Landscape Working of generative ai search
ChatGPT-and-Generative-AI-Landscape Working of generative ai search
 
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
SATELITE COMMUNICATION UNIT 1 CEC352 REGULATION 2021 PPT BASICS OF SATELITE ....
 
me3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part Ame3493 manufacturing technology unit 1 Part A
me3493 manufacturing technology unit 1 Part A
 
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
Quasi-Stochastic Approximation: Algorithm Design Principles with Applications...
 
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
Strategies of Urban Morphologyfor Improving Outdoor Thermal Comfort and Susta...
 
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdfsdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
sdfsadopkjpiosufoiasdoifjasldkjfl a asldkjflaskdjflkjsdsdf
 
Présentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdfPrésentation IIRB 2024 Chloe Dufrane.pdf
Présentation IIRB 2024 Chloe Dufrane.pdf
 
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdfRenewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
Renewable Energy & Entrepreneurship Workshop_21Feb2024.pdf
 
Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Graphics Primitives and CG Display Devices
Graphics Primitives and CG Display DevicesGraphics Primitives and CG Display Devices
Graphics Primitives and CG Display Devices
 
Basic Principle of Electrochemical Sensor
Basic Principle of  Electrochemical SensorBasic Principle of  Electrochemical Sensor
Basic Principle of Electrochemical Sensor
 
cloud computing notes for anna university syllabus
cloud computing notes for anna university syllabuscloud computing notes for anna university syllabus
cloud computing notes for anna university syllabus
 
Multicomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdfMulticomponent Spiral Wound Membrane Separation Model.pdf
Multicomponent Spiral Wound Membrane Separation Model.pdf
 
Design of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptxDesign of Clutches and Brakes in Design of Machine Elements.pptx
Design of Clutches and Brakes in Design of Machine Elements.pptx
 
Test of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptxTest of Significance of Large Samples for Mean = µ.pptx
Test of Significance of Large Samples for Mean = µ.pptx
 
Power System electrical and electronics .pptx
Power System electrical and electronics .pptxPower System electrical and electronics .pptx
Power System electrical and electronics .pptx
 
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdfSummer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
Summer training report on BUILDING CONSTRUCTION for DIPLOMA Students.pdf
 
The relationship between iot and communication technology
The relationship between iot and communication technologyThe relationship between iot and communication technology
The relationship between iot and communication technology
 
Présentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdfPrésentation IIRB 2024 Marine Cordonnier.pdf
Présentation IIRB 2024 Marine Cordonnier.pdf
 

Method overloading

  • 2. • If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
  • 3. • Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a( int, int) for two parameters, and b(int, int ,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. • So, we perform method overloading to figure out the program quickly.
  • 4. Advantage of method overloading • Method overloading increases the readability of the program.
  • 5. Different ways to overload the method • By changing number of arguments • By changing the data type
  • 6. Method Overloading: changing no. of arguments class Adder { static int add(int a, int b) { return a+b; } static int add(int a, int b, int c) { return a+b+c;} }
  • 7. class TestOverloading1 { public static void main(String[] args) { System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); } }
  • 8. • we have created two methods, first add() method performs addition of two numbers and second add method performs addition of three numbers.
  • 9. Method Overloading: changing data type of arguments • class Adder • { • static int add(int a, int b) • {return a+b;} • static double add(double a, double b) • {return a+b;} • }
  • 10. • class TestOverloading2 • { • public static void main(String[] args) • { • System.out.println(Adder.add(11,11)); • System.out.println(Adder.add(12.3,12.6)); • } • }
  • 11. • we have created two methods that differs in data type. The first add method receives two integer arguments and second add method receives two double arguments.
  • 12. Why Method Overloading is not possible by changing the return type of method only? In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur:
  • 13. • class Adder • { • static int add(int a,int b){return a+b;} • static double add(int a,int b){return a+b;} • } • class TestOverloading3{ • public static void main(String[] args){ • System.out.println(Adder.add(11,11));//ambig uity • }}
  • 14. Compile Time Error: method add(int, int) is already defined in class Adder System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be called?
  • 15. Can we overload java main() method?
  • 16. • Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example:
  • 17. class TestOverloading4 { public static void main(String[] args) {System.out.println("main with String[]");} public static void main(String args) {System.out.println("main with String");} public static void main() {System.out.println("main without args");} }
  • 18. Method Overriding in Java • If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. • In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
  • 19. Usage of Java Method Overriding • Method overriding is used to provide specific implementation of a method that is already provided by its super class. • Method overriding is used for runtime polymorphism
  • 20. Rules for Java Method Overriding • method must have same name as in the parent class • method must have same parameter as in the parent class. • must be IS-A relationship (inheritance).
  • 21. Understanding the problem without method overriding • class Vehicle{ • void run(){System.out.println("Vehicle is runn ing");} } • class Bike extends Vehicle{ • public static void main(String args[]){ • Bike obj = new Bike(); • obj.run(); • } }
  • 22. Example of method overriding • class Vehicle{ • void run(){System.out.println("Vehicle is running");} } • class Bike2 extends Vehicle{ • void run(){System.out.println("Bike is running safely");} • public static void main(String args[]){ • Bike2 obj = new Bike2(); • obj.run(); • }
  • 23. super keyword in java • The super keyword in java is a reference variable which is used to refer immediate parent class object.
  • 24. Usage of java super Keyword • super can be used to refer immediate parent class instance variable. • super can be used to invoke immediate parent class method. • super() can be used to invoke immediate parent class constructor.
  • 25. super is used to refer immediate parent class instance variable. • We can use super keyword to access the data member or field of parent class. It is used if parent class and child class have same fields.
  • 26. • lass Animal{ • String color="white"; • } • class Dog extends Animal{ • String color="black"; • void printColor(){ • System.out.println(color);//prints color of Dog class • System.out.println(super.color);//prints color of Animal class • } }
  • 27. • class TestSuper1 • { • public static void main(String args[]) • { • Dog d=new Dog(); • d.printColor(); • }}
  • 28. super can be used to invoke parent class method • The super keyword can also be used to invoke parent class method. It should be used if subclass contains the same method as parent class. In other words, it is used if method is overridden.
  • 29. • class Animal{ • void eat(){System.out.println("eating...");} • } • class Dog extends Animal{ • void eat(){System.out.println("eating bread...");} • void bark(){System.out.println("barking...");} • void work(){ • super.eat(); • bark(); • } }
  • 30. • class TestSuper2 • { • public static void main(String args[]) • { • Dog d=new Dog(); • d.work(); • } • }
  • 31. super is used to invoke parent class constructor. • class Animal{ • Animal(){System.out.println("animal is created");} • } • class Dog extends Animal{ • Dog(){ • super(); • System.out.println("dog is created"); • } • }
  • 32. • class TestSuper3 • { • public static void main(String args[]) • { • Dog d=new Dog(); • } • }