๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java] Static ๋ณ€์ˆ˜

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 18.
๋ฐ˜์‘ํ˜•

โ–ถ Static ๋ณ€์ˆ˜

package staticex;

public class Student {

	public static int serialNum = 1000;  // static ๋ณ€์ˆ˜๋Š” ์ธ์Šคํ„ด์Šค ์ƒ์„ฑ๊ณผ ์ƒ๊ด€์—†์ด ๋จผ์ € ์ƒ์„ฑ๋จ
	public int studentID;
	public String studentName;
	public int grade;
	public String address;

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String name) {
		studentName = name;
	}

}
package staticex;

public class StudentTest1 {
	public static void main(String[] args) {

		Student studentLee = new Student();
		studentLee.setStudentName("์ด์ง€์›");
		System.out.println(studentLee.serialNum);  // ์ดˆ๊นƒ๊ฐ’ ์ถœ๋ ฅ
		studentLee.serialNum++;  // static ๋ณ€์ˆ˜ ์ฆ๊ฐ€

		Student studentSon = new Student();
		studentSon.setStudentName("์†์ˆ˜๊ฒฝ");
		System.out.println(studentSon.serialNum);  // ์ฆ๊ฐ€๋œ ๊ฐ’ ์ถœ๋ ฅ
		System.out.println(studentLee.serialNum);  // ์ฆ๊ฐ€๋œ ๊ฐ’ ์ถœ๋ ฅ
	}
}

<๊ฒฐ๊ณผ๊ฐ’>

โ€‹

 

 

-ํ•™๋ฒˆ ์ƒ์„ฑํ•˜๊ธฐ

package staticex;

public class Student1 {

	public static int serialNum = 1000;
	public int studentID;
	public String studentName;
	public int grade;
	public String address;

	public Student1() {
		serialNum++;  // ํ•™์ƒ์ด ์ƒ์„ฑ๋ ๋•Œ๋งˆ๋‹ค ์ฆ๊ฐ€
		studentID = serialNum;  // ์ฆ๊ฐ€๋œ ๊ฐ’์„ ํ•™๋ฒˆ ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜์— ๋ถ€์—ฌ
	}

	public String getStudentName() {
		return studentName;
	}

	public void setStudentName(String name) {
		studentName = name;
	}

}

 

package staticex;

public class StudentTest2 {
	public static void main(String[] args) {

		Student1 studentLee = new Student1();
		studentLee.setStudentName("์ด์ง€์›");
		System.out.println(studentLee.serialNum);
		System.out.println(studentLee.studentName + " ํ•™๋ฒˆ:" + studentLee.studentID);

		Student1 studentSon = new Student1();
		studentSon.setStudentName("์†์ˆ˜๊ฒฝ");
		System.out.println(studentSon.serialNum);
		System.out.println(studentSon.studentName + " ํ•™๋ฒˆ:" + studentSon.studentID);
	}
}
package staticex;

public class StudentTest3 {
	public static void main(String[] args) {

		Student1 studentLee = new Student1();
		studentLee.setStudentName("์ด์ง€์›");
		System.out.println(Student1.serialNum);  // serialNum ๋ณ€์ˆ˜๋ฅผ ์ง์ ‘ ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ์ฐธ์กฐ
		System.out.println(studentLee.studentName + " ํ•™๋ฒˆ:" + studentLee.studentID);

		Student1 studentSon = new Student1();
		studentSon.setStudentName("์†์ˆ˜๊ฒฝ");
		System.out.println(Student1.serialNum);  // serialNum ๋ณ€์ˆ˜๋ฅผ ์ง์ ‘ ํด๋ž˜์Šค ์ด๋ฆ„์œผ๋กœ ์ฐธ์กฐ
		System.out.println(studentSon.studentName + " ํ•™๋ฒˆ:" + studentSon.studentID);
	}
}

ํด๋ž˜์Šค. ํด๋ž˜์Šค ๋ณ€์ˆ˜ โ—‹

์ธ์Šคํ„ด์Šค. ํด๋ž˜์Šค ๋ณ€์ˆ˜ โ—‹

ํด๋ž˜์Šค. ์ธ์Šคํ„ด์Šค ๋ณ€์ˆ˜ X

๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€