티스토리 뷰

반응형

1. 클래스(class)

-- 클래스 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 클래스 생성 
public class Student {
    String name;  // 객체 변수(인스턴스 멤버, 멤버 변수, 속성)
    
    public void setName(String name) { // 메소드(Method)
        this.name = name;
    }
    
    public static void main(String[] args) { 
        Student stu1 = new Student();  // cat 객체 생성, student의 인스턴스(instance)
        stu1.setName("Aaron");
        System.out.println(stu1.name);  // 객체 변수의 값 확인   
    }
}
cs



2. 메소드(method)

-- 메소드 생성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class MethodTest {
    public int sum(int a, int b) {  // 일반 메소드 
        return a+b;
    }
    public void noReturn(int a, int b) {  // 리턴값이 없는 메소드   
        System.out.println(a+" + "+b+" = "+(a+b));
    }
    public String say() {  // 입력값이 없는 메소드  
        return "Hi";
    }
    public void say2() {  // 입력, 리턴값이 없는 메소드 
        System.out.println("Hi2");
    }
    
    public static void main(String[] args) { 
        int n1 = 10;
        int n2 = 20;
        
        MethodTest mt = new MethodTest();
        int s = mt.sum(n1, n2);  // 메소드 사용 
        
        System.out.println(s); // 30
        System.out.println(mt.say());  // Hi
        mt.noReturn(3040);  // 30 + 40 = 70
        mt.say2(); // Hi2
    }
}
 
cs


-- 객체를 메소드에 전달하여 객체변수 값을 변경

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MethodTest {
    int n;  //객체 변수  
    
    public void plus(MethodTest mt) {   
        mt.n++;  // 전달받은 객체의 객체변수 값을 변경
    }
    
    public static void main(String[] args) { 
        MethodTest myMT = new MethodTest();
        myMT.n = 1;
        myMT.plus(myMT);
        System.out.println(myMT.n);
    }
}
 
cs


-- 메소드에서 직접 객체에 접근하여 객체변수 값을 변경

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MethodTest {
    int n;  // 객체 변수  
    
    public void plus() {   
        this.n++; // 객체에 접근하여 객체변수 값을 변경
    }
    
    public static void main(String[] args) { 
        MethodTest myMT = new MethodTest();
        myMT.n = 1;
        myMT.plus();
        System.out.println(myMT.n);
    }
}
cs


3. Call By Value

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Bonus {
    public void bonus(MyPay myPay) {
        myPay.pay++;  // 전달받은 객체의 객체변수(속성) 값을 변경
    }
}
 
public class MyPay {
    int pay = 100;
    public static void main(String[] args) {
        MyPay beforePay = new MyPay(); 
        
        Bonus afterPay = new Bonus();
        afterPay.bonus(beforePay); // 메소드에 객체를 전달 
    }
}
cs



--

--

--

--

반응형
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday