자동형변환 , 메서드 재정의
필드 : 클래스나 객체의 속성을 저장 . 객체가 생성될때 함께 생성
지역변수 : 함수나 메서드 내부에서 선언된 값을 저장하는 공간
public class Student{
String name; //필드
void method1() {
String name = null; //지역변수
System.out.println(name); //name은 지역변수
}
void method2() {
System.out.println(name); //name은 필드
}
}
✔ method1()을 호출하면 지역변수 name 생성, print문 출력 후 사라진다.
생성자가 없으면 기본 생성자가 컴파일 시 자동으로 추가(존재)
public class Student{
String name;
//생성자가 없으면 자동 추가(코드에 보이는 것이 아니라 항상 존재 한다고 생각하기)
public Student(){
}
void method1() {
String name = null;
System.out.println(name);
}
void method2() {
System.out.println(name);
}
}
그렇기 때문에 우리는 생성자를 클래스 안에 작성하지 않았어도 생성자 호출이 가능한것이다
Student s1 = new Student() // 기본 생성자 호출
생성자 오버로딩이 많아지면 중복된 코드가 발생한다. 공통 코드를 한 생성자(매개변수가 많은)에게만 작성하고 나머지 생성자는 thid(..)를 이용하여 생성자를 호출하는 방법으로 사용
Car (String model){
this.model = model;
this.color = "은색";
this.speed = 250;
}
Car (String model, String color){
this.model = model;
this.color = this.color;
this.speed = 250;
}
Car (String model, String color, in speed){
this.model = model;
this.color = this.color;
this.maxSpeed = this.speed;
}
Car (String model){
this(model, "빨간색", 300);
}
Car (String model, String color){
this(model, color, 2400);
}
Car (String model, String color, in speed){
this.model = model;
this.color = this.color;
this.maxSpeed = this.speed;
}
객체를 생성해야만 사용할 수 있는 멤버
여태까지 봤던 생성자 안에 필드와 메소드가 다 인스턴스 멤버다
객체 없이도 사용 가능한 멤버
✔ 정적 멤버는 내부에 인스턴스 필드나 메소드 사용 불가 하며 this도 사용 불가
ctrl + shift + o(영어)

String, Math 등 따로 import 하지 않아도 되는 이유는 java.lang 패키지 안에 있기 때문이다.
package ch06.sec15;
public class SingletonExample {
public static void main(String[] args) {
Singleton obj1 = Singleton.getInstance(); //정적 메소드는 클래스.메소드
Singleton obj2 = Singleton.getInstance();
if(obj1 == obj2) {
System.out.println("같은 객체입니다"); //주소값이 동일
}else {
System.out.println("ㄴㄴ");
}
}
}
getInstance()로 가져온 생성자들을 비교 하면 모두 다 같은 객체 == 주소값이 다 같음
package ch06.sec15;
public class Singleton {
private static Singleton singleton = new Singleton();
public static Singleton getInstance() { // 생성자 1개로 활용함
return singleton;
}
private Singleton() { // new Singleton 할때 실행됨. 딱 1번
System.out.println("생성자 실행");
}
}