본문 바로가기
Language/JAVA

[JAVA] 메소드 1~9 method , class, static, instance

by 아이엠제니 2022. 2. 6.

부스트코스 생활코딩 [쉽게 배우는 자바2] 공부 기록

 

 

1. 수업소개

method = function = subroutine = procedural

procedural programming (절차 지향 프로그래밍)

자바에서는 method programming

작은 부품을 만들고, 결합하여 만든다.

 

method와 variable을 결합하여 class로 정리정돈

정리정돈 상자를 통해 구조화하여 만드는 게 object oriented programming (객체 지향 프로그래밍)

 

 

 

2. 이미 익숙한 메소드

public class FirstMethod {
    public static void main(String[] args) {
        System.out.println("Hello Method");
        System.out.println(Math.floor(1.1));
    }
}

이미 입력했었음!

main, println, Math 등등

 

 

 

3. 메소드의 기본 형식

package javaChapter2_9;

public class WhyMethod {

    public static void printTwoTimesA() {
        System.out.println("-");
        System.out.println("A");
        System.out.println("A");
    }
    public static void main(String[] args) {
        // 100000000
        printTwoTimesA();
        // 100000000
        printTwoTimesA();
        // 100000000
        printTwoTimesA();
    }
}

코드가 1억줄이라면,,,?

메소드화해서 한 번에 교체할 수 있는 폭발적인 효과를 얻을 수 있다!!!

 

 

 

4. 메소드의 입력

package javaChapter2_9;

public class WhyMethod {
    
    public static void main(String[] args) {
                    // 인자, argument
        printTwoTimes("a","&");
        // 100000000
        printTwoTimes("b","*");
    }
                                    // 매개변수, parameter
    public static void printTwoTimes(String text, String delimiter) {
        System.out.println(delimiter);
        System.out.println(text);
        System.out.println(text);
    }
}

파라미터 값에 따라 다른 결과를 만드는 메소드를 만들 수 있음.

Main 메소드가 있어야, 코드를 실행할 수 있음.

 

 

 

5. 메소드의 출력

 

package javaChapter2_9;

public class OutputMethod {

    public static String a() {
        return "a";
    }

    public static int one() {
        return 1;
    }
    public static void main(String[] args) {

        System.out.println(a());
        System.out.println(one());

    }
}

return으로 값 출력.

return은 종료시키는 기능도 하기 때문에, return 뒤에 아무리 긴 코드를 넣어도 실행되지 않는다.

 

public static 뒤에 어떤 데이터 타입을 return 할 것인지에 따라 데이터 타입을 넣어줘야 한다!

void는 리턴값 ㄴㄴ

 

 

 

package javaChapter2_9;

import java.io.FileWriter;
import java.io.IOException;

public class WhyMethod {

    public static void main(String[] args) throws IOException {
        System.out.println(twoTimes("a", "-"));
        FileWriter fw = new FileWriter("out.txt");
        fw.write(twoTimes("a", "*"));
        fw.close();
//        Email.send("egoing@a.com", "two times a", twoTimes("a","&"));
    }

    public static String twoTimes(String text, String delimiter) {
        String out = "";
        out = out + delimiter + "\n";
        out = out + text + "\n";
        out = out + text + "\n";
        return out;
    }
}

out.txt 파일에 출력

 

 

 

6. 메소드의 활용

package javaChapter2_9;

public class AccountingAppBefore {
    public static void main(String[] args) {
        // 공급가액
        double valueOfSupply = 10000.0;
        
        // 부가가치세율
        double vatRate = 0.1;
        // 부가세
        double vat = valueOfSupply * vatRate;
        // 합계
        double total = valueOfSupply + vat;

        System.out.println("Value of supply : " + valueOfSupply);
        System.out.println("VAT : " + vat);
        System.out.println("Total : " + total);
    }
}

이전에 작성했었던 코드를 메소드를 이용해서 바꿔보기.

package javaChapter2_9;

public class AccountingApp {
    // 공급가액
    public static double valueOfSupply = 10000.0;
    // 부가가치세율
    public static double vatRate = 0.1;

    public static double getVAT() {
        return valueOfSupply * vatRate;
    }

    public static double getTotal() {
        return valueOfSupply + getVAT();
    }

    public static void main(String[] args) {
        
        System.out.println("Value of supply : " + valueOfSupply);
        System.out.println("VAT : " + getVAT());
        System.out.println("Total : " + getTotal());
    }
}

이렇게 바뀌었다.

메인 메소드 안에 복잡하게 들어있던 코드가 간결하게 바뀌었다.

메인 메소드 안에 따로 변수화할 필요 없이, 메소드를 호출하고 바로 출력한다!!

 

 

 

7. 수업을 마치며

8. 부록

Access level modifiers

 

public, protected, default, private

package javaChapter2_9;

class Greeting {
    // public, protected, default, private
    public static void hi() {
        System.out.println("hi");
    }
}

public class AccessLevelModifiersMethod {

    public static void main(String[] args) {
        Greeting.hi();
    }
}

 

private: 같은 클래스 안에서만 사용 가능

다른 클래스에 있는데, private를 사용해서 에러.

 

 

 

9. 부록 (static)

static - class method

no static - instance method

 

static이 있는 메소드는 클래스의 메소드다.

static이 없는 메소드는 인스턴스의 메소드다.

package javaChapter2_9;

class Print {
    public String delimiter;

    public void a() {
        System.out.println(this.delimiter);
        System.out.println("a");
        System.out.println("a");
    }

    public void b() {
        System.out.println(this.delimiter);
        System.out.println("b");
        System.out.println("b");
    }

    public static void c(String delimiter) {
        System.out.println(delimiter);
        System.out.println("c");
        System.out.println("c");
    }
}

public class StaticMethod {
    public static void main(String[] args) {
//        Print.a("-");
//        Print.b("-");

        // instance
        Print t1 = new Print();
        t1.delimiter = "-";
        t1.a();
        t1.b();
        Print.c("$");

//        Print.a("*");
//        Print.b("*");

        Print t2 = new Print();
        t2.delimiter = "*";
        t2.a();
        t2.b();
    }
}

 

300x250