[JAVA] 클래스 | 인스턴스 변수 | 클래스 변수 | 인스턴스 메소드 | 클래스 메소드

·2025년 7월 1일
0

JAVA

목록 보기
9/17

📍 클래스

: 데이터와 기능을 포함하는 코드 묶음

class 클래스명 {
⠀⠀...
}

// defind Person class 
class Person {
	...
}

// Person 클래스로 객체 만들기
public static void main(String[] args) {
	Person person = new Person(); // Person: 클래스명, person: 객체명
}



📍 인스턴스 변수

  • 클래스 내에 선언된 변수

class 클래스명 {
⠀⠀인스턴스 변수1
⠀⠀인스턴스 변수2
⠀⠀...
}

class Person {
	Stirng name; // 인스턴스 변수
    int age; // 인스턴스 변수
}


public static void main(String[] args) {
	Person person = new Person(); 
    person.name = "철수";
    person.age = 20;
}
  • ' . '으로 접근
  • 객체마다 서로 다른 값을 가질 수 있음



📍클래스 변수

  • 클래스 내에 static으로 선언된 변수
  • 모든 객체가 공유하는 변수

class 클래스명 {
⠀⠀static 클래스 변수1
⠀⠀static 클래스 변수2
⠀⠀...
}

class Person {
	String name;
    int age;
    static int personCount = 0; // 클래스 변수
}


public static void main(String[] args) {
	Person.personCount = 10;
    System.out.println(Person.personCount); // 10
} 
  • 객체를 만들 필요 없이 클래스 명으로 접근할 수 있음



📍 인스턴스 메소드

  • 클래스 내에 정의된 메소드

class 클래스명 {
⠀⠀인스턴스 메소드1
⠀⠀인스턴스 메소드2
⠀⠀...
}

class Person {
	String name;
    int age;
    static int personCount = 0;
    public void introduce() {
    	System.out.println("이름: " + name);
        System.out.println("나이: " + age);
    }
}


public static void main(String[] args) {
	Person person = new Person();
    person.name = "철수";
    person.age = 20;
    person.introduct();
}

// 이름: 철수
// 나이: 20



📍 클래스 메소드

  • 클래스 내에 static으로 정의된 메소드

class 클래스명 {
⠀⠀static 클래스 메소드1
⠀⠀static 클래스 메소드2
⠀⠀...
}

class Person {
	String name;
    int age;
    static int personCount = 0;
    
    public static void printPersonCount() {
    	System.out.println(personCount);
    }
}


public static void main(String[] args) {
	Person.personCount = 10;
    Person.printPersonCount();
}

// 10
profile
To Dare is To Do

0개의 댓글