public class Example{
int a = 0; //필드 -> 클래스의 속성 나타내는 변수
void print() { } //메서드 -> 클래스의 기능
Example { } //생성자 -> 클래스의 객체를 생성
class Example_2 { } //이너 클래스 -> 클래스 내부의 클래스
}
class Car {
private String model;
private int wheels;
...
void power() {...}
void stop() {...}
...
}
class CarTest {
public static void main(String[] args)
Car hyundai = new Car(); //Car 클래스 기반으로 생성된 hyundai 인스턴스
Car tesla = new Car(); //Car 클래스 기반으로 생성된 tesla 인스턴스
}
class Car{
public String model;
public int wheels;
public Car(String model, int wheels) { //인스턴스 초기화를 위한 생성자 함수
this.model = model;
this.wheels = wheels;
}
void power(){
---
}
}
class CarTest{
Car hyundai = new Car("sonata", 4); //객체 생성
hyundai.power(); //메서드 호출
}
→ 클래스에 포함된 변수
class Example{
int a; // 인스턴스 변수
static int b; // 클래스 변수
void method() {
int c = 0; // 지역 변수, {} 블록 안에서만 유효
}
}
publid class StaticTest{
psvm {
Static static1 = new Static();
Static static2 = new Static();
static1.num1 = 100;
static2.num1 = 1000;
sout(static1.num1);
sout(static2.num1);
static1.num2 = 200;
static2.num2 = 2000;
sout(static1.num2);
sout(static2.num2);
}
}
class Static {
int num1 = 10;
static int num2 = 20;
}
100
1000
2000
2000
하지만 num2는 클래스 변수이고 static1의 num을 바꾸던 static2의 것을 바꾸던 같은 값을 갖게된다.
public static int add(int x, int y){ // 메서드 시그니처
int result = x+y; // 메서드 바디
return result;
}
class Cal {
public int add() {
}
public int add(a) {
return a;
}
public int add(a,b) {
return a+b;
}
public int add(a,b,c) {
return a+b+c;
}
}