반응형
What is the difference between overriding and overloading in Java? Simply put the difference between them is that method overloading means when methods with the same name but different parameters are usually under one class while the method overriding is when a child class manipulates a method from its parent without changing any parameters.
Overloading VS Overriding
Common
Happens when we manipulate methods with the same name
Differences
Overloading | Overriding |
Extends functionalities of a method with different parameters | Customizes functionalities of the parent method in a child class |
Can be used for inheritance | Must be an inheritance relation |
Different parameters | Same parameters |
Can use different return types | Cannot use different return types |
Can have different access modifier | The child's access modifier can't be less than the parent's |
Can throw different errors | Can't throw different or broader errors |
Overriding Example
Overloading Example
public static int getBucketCount(double width, double height, double areaPerBucket, int extraBuckets) {
if (width <= 0 || height <= 0 || areaPerBucket <= 0) {
return -1;
}
double area = width * height;
double numberOfBucketCal = area / areaPerBucket;
int numberOfBucket = (int) Math.ceil(numberOfBucketCal);
return numberOfBucket + extraBuckets;
}
public static int getBucketCount(double width, double height, double areaPerBucket) {
if (width <= 0 || height <= 0 || areaPerBucket <= 0) {
return -1;
}
double area = width * height;
double numberOfBucketCal = area / areaPerBucket;
int numberOfBucket = (int) Math.ceil(numberOfBucketCal);
return numberOfBucket;
}
public static int getBucketCount(double area, double areaPerBucket) {
if (area <= 0 || areaPerBucket <= 0) {
return -1;
}
double numberOfBucketCal = area / areaPerBucket;
int numberOfBucket = (int) Math.ceil(numberOfBucketCal);
return numberOfBucket;
}
We have seen the difference between method overloading and method overriding.
728x90
반응형
'Backend > Java' 카테고리의 다른 글
Springboot - Sending Emails (0) | 2024.02.10 |
---|---|
Polymorphism (0) | 2024.01.01 |
java: error: release version 21 not supported (0) | 2023.12.30 |
Lombok (0) | 2023.12.29 |
Inheritance (0) | 2023.12.28 |