Override vs Overload, Access modifiers, Abstract class vs Interface.
sobes.tech AI
Answer from AI
Override vs Overload:
-
Override — is when a subclass provides its own implementation of a method that is already defined in the base class with the same name and signature. It allows changing the behavior of the method.
-
Overload — is creating multiple methods with the same name but different parameters (type, number) within the same class. It allows using one name for different operations.
class Example {
void print(int a) { }
void print(String s) { } // overloading
}
class Child extends Example {
@Override
void print(int a) { /* new implementation */ } // overriding
}
Access Modifiers:
- public — accessible from anywhere.
- private — accessible only within the class.
- protected — accessible within the class, its subclasses, and within the package (in Java).
- default (package-private) — accessible within the package (if no modifier is specified).
Abstract Class vs Interface:
-
Abstract class can contain both abstract methods (without implementation) and methods with implementation, as well as fields with state. A subclass inherits the abstract class and must implement the abstract methods.
-
Interface — is a contract that defines a set of methods without implementation (in modern languages, interfaces can contain default methods with implementation). A class can implement multiple interfaces but can inherit only one class.
Usage:
- Abstract class is suitable when there is a common implementation and state that need to be shared.
- Interface — for defining capabilities that can be implemented by different classes without a shared hierarchy.