메서드 선언(실행한 후 결과값을 반환해준다.)
리턴타입 메서드 이름(매개변수1, 매개변수2......n) {
// statement1;
// statement2;
}
- 리턴 타입
~ void test() { } //리턴값이 없는 메서드
~ double test() { } //double 타입의 값을 리턴하는 메서드
~ double test(int x, int y) { }
~ int test(int x) { }
...
- 리턴 값이 있는 메서드의 공통점: 블록문 안에 return 키워드가 존재
package ex03.sampel03;
public class Calculator {
//리턴값이 없는 메서드 선언
void powerOn() {
System.out.println("전원을 켭니다.");
}
void powerOff() {
System.out.println("전원을 끕니다.");
}
int add(int num1, int num2) {
int result = num1 + num2;
return result;
}
double div(int num1, int num2) {
double result = (double)num1 / (double)num2;
return result;
}
}
package ex03.sampel03;
public class CalculatorExample {
public static void main(String[] args) {
Calculator myCal = new Calculator();
myCal.powerOn();
int result1 = myCal.add(10, 6);
System.out.println("result1: " + result1);
double result2 = myCal.div(10, 3);
System.out.println("result2: " + result2);
myCal.powerOff();
}
}
<필드 및 메서드 선언하는 방법에 따라>
- 인스턴스 멤버: 객체 생성 후 사용할 수 있다.
~ 객체에 소속
~ 값이 바뀌는 것은 인스턴스 멤버로 선언하는 것이 좋다.(필드가 바뀌는 것)
~ this
- 정적 멤버: 객체 생성 없이도 사용할 수 있다.
~ 클래스에 소속
~ 값이 바뀌지 않을 때는 정적 멤버로 선언하는 것이 좋다.(필드가 바뀌지 않는 것)
~ static
public class Car { //인스턴스 멤버
int speed;
void setSpeed(int speed) {...}
}
public class Car { // 정적 멤버
static int speed;
static void setSpeed(int speed) {...}
}
- 정적 메서드 및 정적 블록에서는 인스턴스 멤버를 사용할 수 없다.
- 만약 사용하고자 한다면 ==> 객체를 먼저 생성하고 참조 변수로 접근해야 한다.
public class ClassName{
int field;
void method() {...}
static int field1;
static void method1() {...}
static {
ClassName obj = new ClassName();
obj.field = 10;
obj.method();
field1 = 20;
method1();
}
static void method2() {
ClassName obj2 = new ClassName();
obj2.field = 10;
obj2.method()
field1 = 20;
method1();
}
}
!Quiz!
package ex04.sample04;
public class Pet {
String type;
int age;
void move() {
System.out.println(this.type + "가 움직인다.");
}
}
package ex04.sample04;
public class PetExample {
public static void main(String[] args) {
Pet myPet1 = new Pet();
myPet1.type = "강아지";
myPet1.age = 10;
Pet myPet2 = new Pet();
myPet2.type = "고양이";
myPet2.age = 24;
myPet1.move();
myPet2.move();
System.out.println(myPet1.type + "는 " + myPet1.age + "개월입니다.");
System.out.println(myPet2.type + "는 " + myPet2.age + "개월입니다.");
}
}
'자바(JAVA)' 카테고리의 다른 글
이클립스 단축키 (0) | 2022.10.11 |
---|---|
[자바(Java)] 상속 (0) | 2022.10.07 |
[자바(Java)] 멤버 필드 vs 지역 변수(로컬 변수) (0) | 2022.10.04 |
[자바(Java)] 초기화, 메서드 오버로딩 (0) | 2022.09.29 |
[자바(Java)] 사용자 입력(Console input) (0) | 2022.09.27 |