[ static ]
1. static메소드(정적메소드)
- 일반멤버메소드는 객체를 생성한 후에 사용할 수 있지만
static메소드는 객체 생성없이 <클래스명>으로 호출해서
사용한다.
- 일반멤버변수(인스턴스변수)는 사용할수 없고 static멤버만 사용할 수 있다.
- this를 사용할 수 없다.
- 만드는 방법 : 메소드앞에 static을 붙여서 만든다.
- 인스턴스변수를 사용하지 않는 독립적인 작업의 메소드를 만들때 static메소드를 만든다.
class MyMath{
private int a;
public static int add(int x,int y) {
//a=x+y; //에러 -> static멤버가 아니면 사용못함
//abs(10); //오류
//max(1,2); //가능
return x+y;
}
public static int max(int x,int y) {
return (x>y)?x:y;
}
public int abs(int x) {
return (x>0)?x:-x;
}
}
public class Test02_static {
public static void main(String[] args) {
// add메소드와 max메소드를 사용해서 임의의 두수중 두수합,두수중큰값을 구해서 출력해 보세요
// MyMath m=new MyMath();
// int b=m.add(10, 20);
// System.out.println("두수합:" + b);
// System.out.println("두수중 큰값:" + m.max(10,20));
int a=MyMath.add(1, 2);
System.out.println("두수합:" + a);
System.out.println("두수중큰값:" + MyMath.max(1, 2));
}
}
class MyClass{
private int a;//인스턴스변수
private static int b;//클래스변수(정적변수)
public MyClass() {
a++;
b++;
}
public void print() {
System.out.println("a:" + a);
System.out.println("b:" + b);
}
public static int getB() {
return b;
}
}
public class Test03_static {
public static void main(String[] args) {
MyClass c1=new MyClass();
c1.print();
MyClass c2=new MyClass();
c2.print();
MyClass c3=new MyClass();
c3.print();
System.out.println("생성된 객체수:"+ MyClass.getB());
}
}