클래스 CLASS_Part2

2022. 3. 2. 17:00·Programing/JAVA
목차
  1. (멤버)메서드
  2. 가변 인자 메소드(Variable Arguments)
  3. static 메소드와 인스턴스 메소드
  4. 생성자 constructor

(멤버)메서드

  • http://thedata.kr/thecoding/java/function

가변 인자 메소드(Variable Arguments)

  • 인자 앞에 ..을 붙임,
  • 배열처럼 처리
void printInfo(String ...infos){
    System.out.println(infos[0]);
}
package chapter07;

public class VariableArgument {
    /**
     * Variable Argument Test
     */
    void printInfo(String ...infos){
        if(infos.length != 0){
            for(int i=0;i<infos.length;i++){
                System.out.println(infos[i]);
            }
        }
        else{
            System.out.println("인자가 없네요.");
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        VariableArgument vt = new VariableArgument();
        System.out.println("인자 없이");
        vt.printInfo();
        System.out.println("인자 하나");
        vt.printInfo("aaa");
        System.out.println("인자 두 개");
        vt.printInfo("aaa","bbb");
        System.out.println("인자 세 개");
        vt.printInfo("aaa","bbb","ccc");
    }
}

메서드 오버로딩 overloading

  • 같은 이름의 메소드를 한 클래스에 여러 개 정의 할 수 있는 기능
  • 파라미터 타입이나 개수가 달라야 함

오버로딩 메서드 println()

  • 클래스나 메서드 정의로 이동 : ctrl + 클래수, 메서드 클릭
package chapter07;

public class Overloading2 {

    public static void main(String[] args) {

        System.out.println(1);
        System.out.println(5.5);
        System.out.println((long)100);
        System.out.println("홍길동");
        System.out.println('a');
        System.out.println(true);
        System.out.println(new Overloading2());
        System.out.println(new int[5]);

    }

}

multiply() 메서드 오버로딩

package chapter07;

public class Overloading {

    public static void main(String[] args) {

        Operator op = new Operator();

        System.out.println(op.multiply(4, 3));
        System.out.println(op.multiply(4.5, 3.5));
        System.out.println(op.multiply(4, 3.5));
        System.out.println(op.multiply(4.5, 3));

    }

}

class Operator {

    int multiply(int x, int y) {
        System.out.println("(int, int)");
        return x * y;
    }

    double multiply(double x, double y) {
        System.out.println("(double, double)");
        return x * y;
    }

    double multiply(int x, double y) {
        System.out.println("(int, double)");
        return x * y;
    }

    double multiply(double x, int y) {
        System.out.println("(double, int)");
        return x * y;
    }
}

static 메소드와 인스턴스 메소드

  • static 메소드는 정의 부분 앞에 static 예약어가 지정된 메소드
  • static 메소드는 객체 생성 없이 클래스이름.메서드이름() 으로 호출 가능
  • static 메소드는 인스턴스 메서드나 변수를 바로 호출 할 수 없음
package chapter07;

public class StaticMethod {

    static int sVar; // static 변수
    int iVar; // instance 변수

    // static 메서드에선 호출 가능
    public static void staticCall() {

        System.out.println("staticCall()");
        System.out.println("sVar="+ sVar);
        //instannceCall(); // error : new 해서만 부를 수 있음
        //System.out.println("iVar="+ iVar);// error : new 해서만 사용가능
    }

    // new 생성 후 호출 가능
    public void instanceCall() {
        System.out.println("instantCall()");
        System.out.println("iVar=" + iVar);
    }

    public static void main(String[] args) {
        // static
        staticCall();
        System.out.println("main() - staticVar="+StaticMethod.sVar);
        System.out.println("main() - staticVar="+sVar); // 같은 클래스 : 클래스명 생략 가능

        // new
        StaticMethod sm = new StaticMethod();
        sm.instanceCall();
        System.out.println("main() - var=" +  sm.iVar);
    }

}

생성자 constructor

  • new 연산자와 함께 클래스 인스턴스화 할때 사용되는 리턴타입이 없는 특별한 메소드
  • 멤버 변수 초기화에 사용
  • 정의 하지 않으면 클래스 이름과 같은 기본 생성자 호출
  • 메소드 오버로딩을 통해 생성자 여러개 정의

기본 생성자

  • 생상자에 인자가 없는 생성자
  • 생성자 생략시 불려지는 생성자

클래스 생성

package chapter07;

public class Student {

    // 필드
    String name; // 학생명
    int grade; // 학년
    String department; // 학과

    // 기본 생성자 - 생략가능
    Student() {

    }
}

클래스 사용

package chapter07;

public class StudentMain {

    public static void main(String[] args) {

        Student stu1 = new Student(); // 기본 생성자     
    }
}

생성자 오버로딩

클래스 생성

package chapter07;

public class Student2 {

    // 필드
    String name; // 학생명
    int grade; // 학년
    String department; // 학과

    // 1번 생성자
    Student2() {

    }

    // 2번 생성자
    Student2(String n) {
        name = n;
    }

    // 3번 생성자
    Student2(String n, int g) {
        name = n;
        grade = g;
    }

    // 4번 생성자
    Student2(String n, int g, String d) {
        name = n;
        grade = g;
        department = d;     
    }

    // 학과와 학년을 매개변수로 받는 생성자 (에러 발생)
//  Student(String d, int g) {
//      department = d;     
//      grade = g;
//  }
}

필드 초기화

기본생성자 만 있을때

package chapter07;

public class StudentMain {

    public static void main(String[] args) {

        Student stu1 = new Student(); // 기본 생성자
        // 필드 초기화
        stu1.name = "홍길동";
        stu1.grade = 3;
        stu1.department = "자바";

        Student stu2 = new Student(); // 기본 생성자
        // 필드 초기화
        stu2.name = "임꺽정";
        stu2.grade = 3;
        stu2.department = "파이썬";

    }
}

오버로딩된 생성자 있을때

package chapter07;

public class StudentMain2 {

    public static void main(String[] args) {

        Student stu1 = new Student(); // 1번 생성자
        Student stu2 = new Student("홍길동"); // 2번 생성자
        Student stu3 = new Student("홍길동", 4); // 3번 생성자
        Student stu4 = new Student("홍길동", 4, "소프트웨어공학");

    }
}

'Programing > JAVA' 카테고리의 다른 글

클래스 CLASS_Part4  (0) 2022.03.02
클래스 CLASS_Part3  (0) 2022.03.02
클래스 CLASS_Part1  (0) 2022.03.02
배열 ARRAY  (2) 2022.02.28
함수 - 메서드 FUNCTION  (0) 2022.02.24
  1. (멤버)메서드
  2. 가변 인자 메소드(Variable Arguments)
  3. static 메소드와 인스턴스 메소드
  4. 생성자 constructor
'Programing/JAVA' 카테고리의 다른 글
  • 클래스 CLASS_Part4
  • 클래스 CLASS_Part3
  • 클래스 CLASS_Part1
  • 배열 ARRAY
쿠크
쿠크
  • 쿠크
    쿠크 개발자
    쿠크
  • 전체
    오늘
    어제
    • 분류 전체보기 (76) N
      • Programing (36) N
        • JSP (3)
        • JAVA (23) N
        • Spring (5)
        • HTML (5)
      • 이외 (14) N
        • Git (4) N
        • 임시 잡다함 (6)
        • IntelliJ (1)
        • 에러 모음 (2)
      • OS (11) N
        • Docker (1) N
        • Kubernetes (7) N
        • Linux (3) N
      • DataBase (2)
        • Mysql (1)
      • 토이 프로젝트 (0)
        • 게시판 만들기 (0)
      • Spring (0)
      • 건강 & 생활 (6) N
        • 여름 건강 (6) N
      • 공부 · 자격증 (1)
      • 명언과 루틴 (2) N
      • 부동산 or 주식 (2) N
        • 부동산 (1) N
        • 주식 (1) N
      • 경제 (2) N
  • 인기 글

  • 최근 글

  • 최근 댓글

  • 링크

    • 깃 허브 주소
  • 공지사항

  • 태그

    상속
    쿠버네티스
    java
    DevOps
    spring-framwork
    금리기초 #기준금리 #금리인상 #금리하락 #경제공부 #재테크기초 #생활경제 #경제뉴스이해
    Database
    ubuntu
    kubernetes
    MySQL
    IntelliJ
    jsp
    클래스
    HTML
    하루10분걷기 #걷기운동 #건강습관 #산책효과 #스트레스해소 #수면개선 #힐링루틴 #일상운동
    MVC
    spring
    데브옵스
    error
    Linux
  • hELLO· Designed By정상우.v4.10.3
쿠크
클래스 CLASS_Part2

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.