Static 메서드와 인스턴스 메서드
인스턴스 메서드
- 인스턴스 생성 후, '참조변수.메서드이름()'으로 호출
- 인스턴스 멤버(iv, im)와 관련된 작업을 하는 메서드
- 메서드 내에서 인스턴스 변수(iv) 사용 가능
static 메서드(클래스 메서드) ex) Math.random() Math.round()
- 객체생성없이 '클래스이름.메서드이름()'으로 호출
- 인스턴스 멤버(iv, im)와 관련없는 작업을 하는 메서드
- 메서드 내에서 인스턴스 변수(iv) 사용 불가
clss MyMath2 {
long a, b;
long add() { //인스턴스 메서드
return a+ b; //인스턴스 변수
}
static long add (long a, long b) { //클래스메서드(static 메서드)
return a+b; //가까우니 로컬 변수
}
}
clss MyMathTest2 {
public static void main(String args[]) {
System.out.println(MyMath2.add(200L, 100L); //클래스메서드 호출 (객체 생성없이 호출 가능)
MyMath2 mm = new MyMath2(); //인스턴스 생성 (필요함)
mm.a = 200L;
mm.b= 100L;
System.out.println(mm.add()); //인스턴스메서드 호출
}
}
iv를 쓰게 되는 경우에는 instance 메서드
참보변수를 활용하게 되는 경우는 static 메서드로 통칭해서 외우면 된다!!
메서드 간의 호출과 참조
class TestClass2 {
int iv;
static int cv;
void instanceMethod(){ //객체 생성후 호출 가능
System.out.println(iv);
System.out.println(cv);
}
static void staticmMethod() { //객체 생성없이 호출가능해서, 객체가 있다는 보장이 없음
instanceMethod(); //에러!! 인스턴스메서드를 호출할 수 없다!!
System.out.println(iv); //에러!! 인스턴스 변수를 사용할 수 없다.
System.out.println(cv);
}
}
오버로딩(overloading)
한 클래스 안에 같은 이름의 메서드 여러 개 정의하는 것!
오버로딩의 조건 1. 메서드 이름이 같아야 한다. 2. 매개변수의 개수 또는 타입이 달라야 한다.
3. 반환 타입은 영향 없다.
메서드 : 메서드 이름 = n : 1
예를 들어 println의 경우
void println(), void println(boolean x), void println(char x) ,... 엄청 많다
/
int add (int a, int b ) {return a+b;}
int add (int x, int y ) {return x+y;}
//오버로딩 아닌 중복 정의
int add (int a, int b ) {return a+b;}
long add (int a, int b ) {return laong((a+b);}
//이 경우도 중복정의
long add (int a, long b) {return a+b;}
long add(long a, int b) {return a+b;}
// 이경우는 오버로딩 맞음
생성자(constructor) iv초기화를 편리하게 하려고 하는것이다!!
- 인스턴스가 생성될 때마다 호출되는 '인스턴스 초기화 메서드'
1. 이름이 클래스 이름과 같아야 한다.
2. 리턴값이 없다.(void 안 붙임)
3. 모든 클래스는 반드시 생성자를 가져야 한다.
기본 생성자
- 매개변수가 없는 생성자
- 생성자가 하나도 없을 때만, 컴파일러가 자동 추가
클래스이름() { }
Point() { }
package chap06;
class Data_1 {
int value;
}
class Data_2 {
int value;
Data_2(int x){
value = x;
}
}
public class Ex6_11 {
public static void main(String[] args) {
Data_1 d1 = new Data_1();
Data_2 d2 = new Data_2();
}
}
위 처럼, 생성자를 쓰게 되는 경우에는 기본 생성자를 꼭 정의해줘야 한다! (이름이 문제, 못 찾겠다)
생성자 this() - 생성자는 iv 초기화이기에 목적은 똑같으니 코드 중복제러르 한다.!
- 생서자에서 다른 생성자 호출할 떄 사용
- 다른 생성자 호출시 첫줄에서만 사용 가능!
class Car2 {
String color;
String gearType;
int door;
Car2() {
this("white","auto",4);
}
Car2(String color) {
this(color,"auto",4);
}
Car2(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
clas Car {
Stiring color;
String gearType;
int door;
Car() {
color = "white";
gearType = "auto";
door = 4;
}
//위와 같은 코드를
Car (){
this("white", "auto", 4); //참조 변수 없는 경우 초기화하기 위해 사용!!
}
//this를 통해 중복 제거함
//아래를 호출함!!
Car (String c, String g, int d){
color = c;
gearType = g;
door = d;
}
}
참조 변수 this (this() 와 매우 다르니 유의 할것)
- 인스턴스 자신을 가리키는 참조변수
- 인스턴스 매서드(생성자 포함)에서 사용가능
- 지역 변수(lv)와 인스턴스 변수(iv)를 구별할 때 사용 가능!!
Car(String c, String g, int d) {
color = c;
gearType = g;
door = d;
}
Car(String color, String gearType, int door) {
this.color = color; //this.color는 iv, color는 lv
this.gearType = gearType;
this.door = door;
}
정리!!
참조변수 this와 생성자 this()
this 인스턴스 자신을 가리키는 참조변수, 인스턴스의 주소가 저장되어 있다.
모든 인스턴스메서드에 지역변수로 숨겨진 채로 존재한다. -> this는 생략하면 안된다!!
this(), this(매개변수) 생성자, 같은 클래스의 다른 생성자를 호출할 때 사용한다. (클래스 이름 대신)
인스턴스 메서드에서만 사용 가능!!!
변수의 초기화
지역 변수(lv)는 수동 초기화해야함!!
멤버 변수(iv, cv)는 자동 초기화된다.
1. 명시적 초기화
clas Car{
int door = 4; //기본형 변수의 초기화
Engine e = new Engine(); //참조형 변수의 초기화
}
참조형 변수도 기본형 변수처럼 null을 넣는 것이 아니라 클래스로 초기화를 해야한다!!
2. 초기화 블럭
- 인스턴스 초기화 블럭 {}
- 클래스 초기화 블럭 : static {}
3. 생성자
Car (String color, String gearType, int door) { //매개변수 있는 생성자
this.color = color;
this.gearType = gearType;
this.door = door;
}
cv, iv 초기화
1) 자동 초기화 : null
2) 간단 초기화 : =
3) 복잡 초기화 : {}, static {}, 생성자
멤버 변수의 초기화 - static {}
1. 명시적 초기화(=)
2. 초기화 블럭 - {}, static{}
3. 생성자(iv 초기화)
class StaticBlockTest {
static int[] arr = new int[10]; //명시적 초기화
static { //클래스 초기화 블럭 - 배열 arr을 난수로 채운다.
for (int i = 0; i<arr.lenght; i++){
arr[i] = (int)(Math.random()*10)+1;
}
}
}
멤버 변수의 초기화
- 클래스 변수 초기화 시점 : 클래스가 처음 로딩될 때 한번
- 인스턴스 변수 초기화 시점 : 인스턴스가 생성될 때마다
class InitTest {
static int cv = 1; //명시적 초기화
int iv = 1; //명시적 초기화
static { cv =2;} // 클래스 초기화 블럭
{iv = 2;} // 인스턴스 초기화 블럭
InitTest() { //생성자
iv = 3;
}
}
cv -> iv / 자동 -> 간단 -> 복잡
'Develope_Web&App' 카테고리의 다른 글
[Java ] 내부 클래스 (0) | 2021.02.02 |
---|