Câu hỏi phỏng vấn Java
Câu hỏi

What is Function Overriding and Overloading in Java?

Câu trả lời

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

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:

  • The method in the subclass must have the same name, return type, and parameter list as the method in the superclass.
  • Overriding enables Java's dynamic method dispatch—during runtime, the method that is to be executed is determined by the type of the object, not the type of the reference variable.
  • The @Override annotation is commonly used to indicate that a method is intended to override a method in a superclass.
  • Access level can't be more restrictive than the method being overridden.
  • Only instance methods can be overridden, not static methods.
  • A method marked as final cannot be overridden.

Example:

java Copy
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

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:

  • Overloaded methods must have different argument lists.
  • They can have different...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What is the difference between public , protected , package-private and private in Java?

middle

What differences exist between Iterator and ListIterator ?

entry

What is the difference between an Applet and a Java Application?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào