public class Main {
public static void main(String[] args) {
//method = a block of code that is executed whenever it is called
String name = "Bro";
for(int i=1; i<name.length();i++) {
hello(name);
}
}
static void hello(String name) {
System.out.println("Hello " + name);
}
}
Example
package overriding;
public class Main {
public static void main(String[] args) {
// overloaded methods = methods that share same name but have different parameters
// method name + parameters = method signature
int x = add(1,2);
int y = add(1,2,3);
int z = add(1,2,3,4);
System.out.println(x);
System.out.println(y);
System.out.println(z);
double x2 = add(1.0, 2.0, 3.0, 4.0);
System.out.println(x2);
}
static int add(int a, int b) {
System.out.println("This is overloaded method #1");
return a+b;
}
static int add(int a, int b, int c) {
System.out.println("This is overloaded method #2");
return a+b+c;
}
static int add(int a, int b, int c, int d){
System.out.println("This is overloaded method #3");
return a+b+c+d;
}
static double add(double a, double b) {
System.out.println("This is overloaded method #1");
return a+b;
}
static double add(double a, double b, double c) {
System.out.println("This is overloaded method #2");
return a+b+c;
}
static double add(double a, double b, double c, double d){
System.out.println("This is overloaded method #3");
return a+b+c+d;
}
}
Example
Instead of defining two methods that should do the same thing, it’s better to overload one.
두 개의 메소드를 생성하는 것 대신에, 하나를 overload하는 것이 더 적절하다.
In the example below, we overload the plusMethod method to work for both int and double:
하기 코드에선 plusMethod가 int와 double 두 가지 변수에 대해 작동할 수 있다.
public class Main2 {
public static void main(String[] args) {
int myNum = plusMethod(5,10);
double myNum2 = plusMethod(5.0,4.0);
System.out.println(myNum + " " + myNum2);
}
static int plusMethod(int x, int y) {
return x + y;
}
static double plusMethod(double x, double y) {
return x + y;
}
}
좋은 글 감사합니다.