on
Java 클래스3 패키지, array, static, sigletondesign
Java 클래스3 패키지, array, static, sigletondesign
import java.util.Arrays;
class Counter{
int num; //인스턴스 변수 : new객체생성후 사용, 자동초기화, 초기값 필요없음, 참조변수접근, 객체별로 따로 생성
static int count;
//ststic변수 : main(new객체생성전)실행되기전 생성, 자동초기화, 클래스이름.static변수 이름으로 접근
//객체와 상관없는 유일변수, 객체간의 공유변수로 사용
public Counter() {
num + + ;
count + + ;
}
public int getNum() {
return num;
}
// public static int getNum2() {
// return num;//num은 int멤버변수로 정의됨, static함수에서는 객체생성후 사용되는 멤버변수(int형같은거) 사용불가
// }
public int getCount() { //멤버함수에서 static변수사용
return count;
}
public static int getCount2() { //static함수 : new전에 함수를 사용하도록 준비해줌, 클래스이름.함수이름
return count;
}
}
public class Test {
public static void main( String [] args) {
Counter t1 = new Counter(); //num : 1, count : 1
Counter t2 = new Counter(); //num : 1, count : 2
//t1과 t2의 num은 다르다! but static변수인 count는 객체생성과 관계없음 즉, t1과t2의 count는 같은 count
System . out . println (t1.getNum() + "\t" + t2.getCount()); //num : 1, count : 2
System . out . println (t2.getNum() + "\t" + t1.getCount()); //num : 1, count : 2
System . out . println ( "==========================================" );
Counter.count + + ;
System . out . println (t1.getNum() + "\t" + t2.getCount()); //num : 1, count : 3
System . out . println (t2.getNum() + "\t" + t1.getCount()); //num : 1, count : 3
Counter.getCount2();
//다른 클래스에서 ( 클래스이름.함수이름 ) 으로 호출 가능 원래같음 t1.getCount2 뭐이런식이였을거였는데..
System . out . println ( "==========================================" );
int x = Integer. parseInt ( "10" ); //
//Integer는 java.lang에 속해있는 클래스인데 java.lang은 자동 임포트됨
//Interger클래스의 parseInt는 static 메소드이기 때문에 바로 호출해서 사용가능
//뭐 이런식이다..
int [] k = { 10 , 2 , 3 , 5 , 6 };
Arrays.fill(k, 100 );
for ( int i : k) {
System . out . println (i);
}
}
from http://cocoshin.tistory.com/17 by ccl(A) rewrite - 2021-11-18 02:01:34