Anda di halaman 1dari 10

CHANDIGARH UNIVERSITY

University Institute of Engineering


Department of Computer Science &Engineering

Method Overriding and Overloading

Prepared By- Vijay Kumar


Assistant Professor
CSE Department
Learning Objectives
To understand the concept of method
overloading and method overriding in
java

UIE, ECE Deptt.


2
Topics to be covered
Method Overriding

Rules for Method Overriding

Method Overloading

Questions to be Discussed

UIE, CSE Deptt.


3
Method Overriding
Method with the same name, arguments and return type in
both the parent and the child class

If an overridden method is called from subclass object , it will always refer to


the version defined by the subclass

The version of the method defined by the superclass is hidden or


overridden

Need to Override If a sub class needs have a


different method implementation from that of a super
class

UIE, CSE Deptt.


4
Rules for Method Overriding
Argument list should be same.

Return type should be same

Final methods cannot be overridden.

Constructor can not be overridden

UIE, CSE Deptt.


5
Method Overriding

Draw() and
erase() in Base
Class

Draw() and
erase() in
Derived Class
UIE, CSE Deptt.
6
Dynamic Method Dispatch or Runtime
Polymorphism

Basis of one of Javas most powerful concepts: dynamic method


dispatch

Dynamic method dispatch occurs when the Java language resolves


a call at runtime

Runtime polymorphism is possible in java using

superclass reference variables


overridden methods

UIE, CSE Deptt.


7
Method Overloading
Allows to define the method with the same name but
either return type or arguments list should be different

Class BasicCalculator{
Void sum(int a,int b){
System.out.println(a+b);
}
Void sum(int a,int b,int c){
System.out.println(a+b+c);
}

UIE, CSE Deptt.


8
FAQ
Can we overload static method in Java?

Can we override static method in Java?

Can you prevent overriding a method without using


final modifier?

Can we change return type of method in subclass


while overriding?

UIE, CSE Deptt.


9
References
1. https://www.tutorialspoint.com/java/
java_polymorphism.htm
2. http://www.careerride.com/Object-ori
ented-programming-Interview-Question
s.aspx
3. http://www.javatpoint.com/
4. http://www.java-examples.com/

Anda mungkin juga menyukai