What is Function Overriding and Overloading in Java?
What is Function Overriding and Overloading in Java?
Function overriding and overloading are two fundamental concepts in Java that allow developers to define methods with the same name within a class or across classes with certain differences in their signatures or implementations.
Function overriding occurs when a subclass (child class) provides a specific implementation for a method that is already defined in its superclass (parent class). This is a mechanism by which Java achieves runtime polymorphism, allowing a subclass to tailor a method to its needs or provide a more specific implementation.
Key Points:
@Override
annotation is commonly used to indicate that a method is intended to override a method in a superclass.final
cannot be overridden.Example:
class Animal {
public void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
@Override
public void display() {
System.out.println("I am a dog");
}
}
In this example, Dog
overrides the display
method of Animal
. When you call display
on an object of type Dog
, the overridden method in Dog
is executed.
Function overloading, also known as method overloading, allows a class to have more than one method with the same name, as long as their parameter lists are different. This can mean a different number of parameters, different types of parameters, or both. Overloading is a way to achieve compile-time polymorphism.
Key Points:
junior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào