Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | 4 | 5 | 6 | |
| 7 | 8 | 9 | 10 | 11 | 12 | 13 |
| 14 | 15 | 16 | 17 | 18 | 19 | 20 |
| 21 | 22 | 23 | 24 | 25 | 26 | 27 |
| 28 | 29 | 30 |
Tags
- for문
- 반복문
- 접근제어지시자
- 생성자
- 포함관계
- 자바 멀티스레딩
- OPP개념
- 연관관계
- While
- 인텔리제이 기초 설정
- java변수
- 시스템 환경 변수 편집
- 상수
- multi-threading
- continue문
- JAVA기초
- 형 변환
- this예약어
- 인텔리제이 한글 깨짐 해결법
- IntelliJ IDEA
- function
- Thread
- 집합관계
- Java데이터 타입
- 컴파일
- 메서드
- Java
- break문
- JAVA객체지향
- 메서드 오버로딩
Archives
- Today
- Total
최원종의 개발 블로그
static함수 본문
static메서드(함수)는 특정 클래스의 인스턴스에 속하지 않고 클래스 자체에 속함.
객체를 생성하지 않고도 클래스 이름을 통해 직접적으로 호출할 수 있음.
static 함수 클래스의 모든 인스턴스가 공유하며, 주로 유틸리티 기능이나 공통 동작을 제공하는 데 사용됨.
static 특징
- 객체 생성 없이 호출 가능
- 인스턴스 변수에 접근 불가
- static 함수는 객체의 인스턴스 변수에 직접적으로 접근할 수 없다.
- 왜냐하면 static 함수는 객체가 생성되기 전에 호출될 수 있기 때문에 해당 객체의 상태를 알 수 없기 때문이다.

static 코드 실습
-Calculator ( static함수와 일반 인스턴스 메소드 차이)
package com.tenco_static;
public class Calculator {
//두 수의 합을 받환하는 static 함수
//객체마다 결과가 달라질 이유가 없으므로 static 함수가 적합합니다.
public static int add(int n1, int n2) {
return n1 + n2;
}
// 일반 인스턴스 메소드(객체를 생성해야 사용 가능)
public int multiply(int n1, int n2) {
return n1 + n2;
}
}
-CalculatorTest
package com.tenco_static;
public class CalculatorTest {
//메인 함수(stack 메모리에 할당 됨)
public static void main(String[] args) {
//1 객체 생성 없이 클래스 이름으로 바로 호출 됨
int result1 = Calculator.add(10, 20);
System.out.println("result1 : " + result1);
//2.multiply는 static이 아니므로 객체를 만들어야함
Calculator cal = new Calculator();
int result2 = cal.multiply(10, 20);
System.out.println("result2 : " + result2);
}
}
-BankAccount(전체 계좌 수를 반환하는 기능)
package com.tenco_static;
public class BankAccount {
private static int totalAccounts = 0; //공유변수
private String owner; //멤버변수
private int number;
public BankAccount(String owner) {
this.owner = owner;
totalAccounts++;//계좌 생성시 공유 변수 증가
}
//static 함수 : 전체 계좌 수를 반환하는 기능
public static int getTotalAccounts(){
//static 내부 임
//인스턴스 변수
// owner = "홍길동";
// return this.number;
return totalAccounts;
}
public void showInfo(){
System.out.println("오너 이름 : " + owner);
System.out.println("카드 넘버 : " + number);
}
}
- BankAccountMain (객체 생성 전 클래스 이름으로 접근 가능)
package com.tenco_static;
public class BankAccountMain {
public static void main(String[] args) {
//1. 객체 생성하기 전에 클래스 이름으로 접근 가능
int result1 = BankAccount.getTotalAccounts();
System.out.println("result : " + result1);
BankAccount bankAccount = new BankAccount("홍길동");
}
}
-LottoNumberMaker(멤버변수, static함수 위치와 static함수 안에서 멤버 변수/메서드 접근 가능 여부)
static 함수는 객체가 생성되기 전에도 호출될 수 있다
하지만 멤버 변수(version)는 객체가 생성되어야만 heap영역에 존재 함으로
아직 태어나지도 않은 객체 정보를 사용할 수 없다
package com.tenco_static;
import java.util.Random;
public class LottoNumberMaker {
//1멤버변수(인스턴스 변수) : 객체가 생성되어야 Heep에 존재 함
public String version = "1.0.0";
//2. static 함수 : 클래스 로딩 시 Method Area에 즉시 생성됨
public static int makeNumber() {
Random random = new Random();
//난수 발생하는 기능을 호출해보자
//0 ~ 21억 --> 1 ~ 45 --> 하나 생성
//0 ~ 44 까지 중 하나의 난수 발생
int resultNumber = random.nextInt(44) + 1;
//문제 static 함수 안에서 멤버변수/메소드 접근이 가능할까요?
//System.out.println(version); 에러발생
//getVersion(); 에러발생
//이유를 서술하시오.
//static 함수는 객체가 생성되기 전에도 호출될 수 있다
//하지만 멤버 변수(version)는 객체가 생성되어야만 heap영역에 존재 함으로
//아직 태어나지도 않은 객체 정보를 사용할 수 없다
return resultNumber;
}
public String getVersion() {
return this.version;
}
}
-LottoGame
package com.tenco_static;
public class LottoGame {
public static void main(String[] args) {
int result1 = LottoNumberMaker.makeNumber();
// System.out.println("[" + result1 + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
System.out.print("[" + LottoNumberMaker.makeNumber() + "]");
}//end of main
}//end of class
로또 응용 문제

-LottoGame2
package com.tenco_static;
public class LottoGame2 {
public static void main(String[] args) {
//[2][20][5]
//도전과제 1.
//로또 6개를 생성하고
//6개의 숫자 중에 가장 큰 수를 마지막으로 보내는 코드를 작성하시오.
int n1 = LottoNumberMaker.makeNumber();
int n2 = LottoNumberMaker.makeNumber();
int n3 = LottoNumberMaker.makeNumber();
System.out.println("정렬 전 : " + n1 + "," + n2 + "," + n3);
//인접한 두 수를 비교하며 가장 큰 수를 뒤로 밀기(버블정렬 원리)
//step 1. 첫번째 수와 두번째 수를 비교
if (n1 > n2) {
//n1이 더 크다면 자리를 바꿈(Swap)
int temp = n1;
n1 = n2;
n2 = temp;
//42, 6 ---> 6, 42 임시 상자에 담아두고 숫자 바꾸기
}
//step2. 두번째 수와 세번째 수 비교
//이 과정을 거치면 n1, n2중에서 큰 녀석이 n2에 와있으므로,
//n2 와 n3를 비교하면 결국 셋 중에 가장 큰 수가 맨 뒤 (n3)로 가게됨
if (n2 > n3) {
int temp = n2;
n2 = n3;
n3 = temp;
}
//step3. 결과출력
System.out.println("정렬 후(최대값 이동) : " + n1 + "," + n2 + "," + n3);
}//end of main
}//end of class
도전과제
package com.tenco_static;
public class LottoGame4 {
public static void main(String[] args) {
//[2][20][5] --> 전체 정령 숫자 갯수 --> n - 1 반복하면 됨
//도전과제.
//로또 6개를 생성하고
//6개의 숫자 중에 가장 큰 수를 마지막으로 보내는 코드를 작성하시오.
//if else 사용해서 만들기
int n1 = LottoNumberMaker.makeNumber();
int n2 = LottoNumberMaker.makeNumber();
int n3 = LottoNumberMaker.makeNumber();
int n4 = LottoNumberMaker.makeNumber();
int n5 = LottoNumberMaker.makeNumber();
int n6 = LottoNumberMaker.makeNumber();
System.out.println("정렬 전 : " + n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
for (int i = 0; i < 6; i++) {
if (n1 > n2) {
int temp = n1;
n1 = n2;
n2 = temp;
}
//step2. 두번째 수와 세번째 수 비교
if (n2 > n3) {
int temp = n2;
n2 = n3;
n3 = temp;
}
if (n3 > n4) {
int temp = n3;
n3 = n4;
n4 = temp;
}
if (n4 > n5) {
int temp = n4;
n4 = n5;
n5 = temp;
}
if (n5 > n6) {
int temp = n5;
n5 = n6;
n6 = temp;
}
System.out.println((i + 1) + "차 정렬 진행 : " + n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
}//end of for
//step3. 결과출력
System.out.println("죄종 정렬 후 결과: " + n1 + "," + n2 + "," + n3 + "," + n4 + "," + n5 + "," + n6);
}//end of main
}//end of class
'Java > Java 객체지향' 카테고리의 다른 글
| 전화번호 관리하는 프로그램 만들기 (0) | 2026.02.27 |
|---|---|
| Array(배열) (0) | 2026.02.27 |
| static키워드 이해 (0) | 2026.02.26 |
| get, set 메서드 (0) | 2026.02.26 |
| this 예약어 사용 방법 3가지 (0) | 2026.02.25 |





