Jam's story
정적멤버와 static 본문
정적멤버
클래스에 고정된 멤버로서 객체를 생성하지 않고 사용할 수 있는 필드와 메소드
객체에 소속된게 아니라 클래스에 소속된 멤버이다.
정적멤버 선언
static 타입 필드
static 리턴 타입 메소드 (매개변수선언 )
인스턴스 필드(변수)를 이용하는 메소드라면 -> 인스턴스 메소드
이용하지 않는 메소드 ->정적 메소드 (외부값 사용)
정적필드와 메소드는 클래스이름.메소드 , 클래스이름.필드 로 접근한다
객체 참조변수로도 접근이 가능하다
하지만 클래스 이름으로 접근하는 것이 좋다
ㅍpackage smhrd;
class Cal{
static double pi=3.1459;
static int plus(int x, int y) {
return x+y;
}
static int minus(int x, int y) {
return x-y;
}
}
public class CalExam {
public static void main(String[] args) {
// TODO Auto-generated method stub
double res1=10*10*Cal.pi;
System.out.println(res1);
int res2=Cal.plus(109,4);
System.out.println(res2);
int res3=Cal.minus(130, 3);
System.out.println(res3);
}
}
정적블록
정적변수를 초기화 하는곳,
생성자안에서 초기화는 할 수없다 .이것은 객체를 만드는 부분이기 때문에
static{
}
package smhrd;
class Cal{
static String company="Samsung";
static String model="LCD";
static String info;
static {
info=company+" and "+model;
}
}
public class CalExam {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Cal.info);
}
}
'자바' 카테고리의 다른 글
final 필드와 상수 (0) | 2022.01.13 |
---|---|
싱글톤 Singleton (0) | 2022.01.07 |
클래스 (0) | 2022.01.05 |
chap5 연습문제 (0) | 2022.01.03 |
열거 (0) | 2022.01.02 |
Comments