1 . 오버로딩
오버로딩이란???
오버로딩은 같은 이름의 함수를 여러개 생성할 때 사용한다.
오버로딩을 사용하기 위한 조건
파라미터의 갯수 또는 타입이 달라야 사용할 수 있다.
매게변수=파라미터=인자 전부 같은 말이다.
📋 코드
package chapter06;
public class ch06_6
{
static int sum(int a, int b)
{
System.out.println("인자가 둘일 경우 호출됨");
return a+b;
}
static int sum(int a, int b, int c )
{
System.out.println("인자가 셋일 경우 호출됨");
return a+b+c;
}
static double sum(double a,double b,double c)
{
System.out.println("double 타입일 경우 호출됨");
return a + b + c;
}
public static void main(String[] args)
{
System.out.println(java.div(3,2));
System.out.println(sum(3,2));
System.out.println(sum(2,3,4));
System.out.println(sum(2.5 , 3.5 , 4.5));
}
}
📕 해설
1. 인자가 둘일 경우 첫번째 sum 실행
2. 인자가 셋일 경우 두번째 sum 실행
3. 인자의 타입이 double 일 경우 세번째 sum 실행
👨🏻💻 결과
인자가 둘일 경우 호출됨
5
인자가 셋일 경우 호출됨
9
double 타입일 경우 호출됨
10.5
2 . 생성자
생성자란??
인스턴스 변수를 초기화 할 때 참조변수를 통해서 일일이 초기화를 해야했다.
하지만 인스턴스 개수가 많아지면 번거로워지기 때문에 생성자를 이용하여 편리하게 관리할 수 있다.
📋 코드
package chapter06;
class Cellphone
{
String model = "Galaxy 8";
String color;
int capacity;
Cellphone(String color, int capacity)
{
this.color = color;
this.capacity = capacity;
}
}
public class ch06_7
{
public static void main(String[] args)
{
//Cellphone myphone1 = new Cellphone();
Cellphone myphone = new Cellphone("Siver", 64);//생성자 호출
System.out.println(myphone.model);
System.out.println(myphone.color);
System.out.println(myphone.capacity);
}
}
📕 해설
1. 멤버 변수: model (모델명), color (색상), capacity (용량)
2. 생성자: color와 capacity를 매개변수로 받아 초기화하는 생성자가 정의되어 있다.
3. Cellphone 객체를 생성하고, 생성자를 통해 color와 capacity를 초기화한 후, 객체의 멤버 변수 값을 출력한다.
👨🏻💻 결과
Galaxy 8
Siver
64
'Java > 단계별 과정' 카테고리의 다른 글
[JAVA] 상속과 다형성 (0) | 2023.05.01 |
---|---|
[JAVA]자바 기본 총정리 (0) | 2023.04.25 |
[JAVA] 배열과 클래스 객체지향 (1) | 2023.04.21 |
[JAVA] 자바 제어문 (if문, if else문, else if문,switch문,for문) (0) | 2023.04.19 |
[JAVA] 자바 프로그래밍의 기본 (0) | 2023.04.18 |