// staitc non-static
/*
* staitc은 non-static을 부를 수 없습니다. non-static은 static을 부를 수 잇습니다. non-static은
* this를 쓸 수 있습니다. static은 this를 쓸 수 없습니다.
*
* static은 클래스를 만든 직후 사용가능합니다.(인스턴스 X)
* non-static은 인스턴스 생성 후 에 사용합니다.
*
* 딱 하나만 만들어서 써야할 때
* 데이터베이스 접속 정보(id, pw, url)
*/
package static01;
//사용해보기
class Car {
final static double PI = 3.14;
String model;
String color;
int speed;
int id;
static int numbers = 0;
public Car(String model, String color, int speed) {
this.model = model;
this.color = color;
this.speed = speed;
this.id = ++numbers;
}
public static void aaa() {
// ccc();
// this.speed = 190;
}// 인스턴스 없이 호출 가능
public void bbb() {
aaa();
this.speed = 190;
}
public void ccc() {
this.model = "ccc";// this 키워드 사용가능
}
}
- Car 클래스:
- final static double PI = 3.14;: 상수(static final) 멤버 PI는 클래스 수준에서 관리되며, 값을 변경할 수 없는 상수로 선언되어 있습니다.
- String model;, String color;, int speed;, int id;: 인스턴스 멤버들은 클래스의 각 인스턴스에 속하는 속성들을 나타냅니다.
- static int numbers = 0;: 정적(static) 멤버 numbers는 모든 인스턴스가 공유하는 클래스 수준의 변수로, 객체가 생성될 때마다 증가하는 차량의 수를 나타냅니다.
- 생성자 public Car(String model, String color, int speed)은 객체가 생성될 때마다 호출되어, 각 인스턴스의 속성을 초기화하고 numbers를 증가시킵니다.
- public static void aaa(): 정적(static) 메서드 aaa()는 인스턴스 생성 없이 호출 가능하며, 정적(static) 메서드에서는 인스턴스 멤버에 직접 접근할 수 없습니다.
- public void bbb(): 인스턴스 메서드 bbb()는 인스턴스를 통해 호출되며, aaa()를 호출하고 speed를 변경합니다.
- public void ccc(): 인스턴스 메서드 ccc()는 인스턴스를 통해 호출되며, this 키워드를 사용하여 인스턴스 멤버에 접근합니다.
public class static02 {
public static void main(String[] args) {
Car car = new Car("i5", "흰색", 150);
Car car2 = new Car("i5", "빨강색", 150);
Car car3 = new Car("i5", "주황색", 150);
Car car4 = new Car("i5", "노랑색", 150);
Car car5 = new Car("i5", "파랑색", 150);
System.out.println(car.id);
System.out.println(car2.id);
System.out.println(car3.id);
System.out.println(car4.id);
System.out.println(car5.id);
System.out.println(Car.numbers);
}
}
- static02 클래스 (main 메서드를 가진 클래스):
- Car car = new Car("i5", "흰색", 150);을 통해 Car 클래스의 인스턴스 car를 생성하고 속성을 초기화합니다.
- Car car2 = new Car("i5", "빨강색", 150);, Car car3 = new Car("i5", "주황색", 150); 등을 통해 다른 차량 인스턴스들을 생성합니다.
- System.out.println(car.id);와 같이 인스턴스의 속성을 출력하여 각 차량의 고유한 ID를 확인합니다.
- System.out.println(Car.numbers);를 통해 정적(static) 멤버인 numbers를 출력하여 생성된 차량의 수를 확인합니다.
1
2
3
4
5
5
'2023.11.21-2024.05.31' 카테고리의 다른 글
231218 JAVA Animal, Cat, Dog, Zoo (0) | 2023.12.19 |
---|---|
231218 JAVA Inheritance(상속) (0) | 2023.12.19 |
231218 JAVA static01(인스턴스 멤버, 정적 멤버) (0) | 2023.12.19 |
231218 JAVA Human AM02(접근제어자 연습) (0) | 2023.12.19 |
231218 JAVA Access Modigiers(접근제어자) (0) | 2023.12.19 |