클래스(class)란 객체 지향 프로그래밍의 추상화(abstraction)라는 개념을 직접 구현.
개발자의 편의를 위해 유용하게 사용할 수 있는 많은 수의 클래스를 미리 정의하여 제공.
또한, 개발자가 원하는 동작을 하는 새로운 클래스를 손쉽게 작성가능
//비어있는 객체 생성
var person1 = new Object();
//person1객체의 프로퍼티를 할당
person1.name = 'michelle'
person1.age = 27
person1.sayHello = function(){
console.log(this.name + 'Hello!');
}
console.log(person1);
person1.job = 'developer';
person1.hobby = 'movie';
var person1 = {
name : 'michelle',
age : 27,
sayHello : function(){
console.log(this.name + 'Hello!');
}
};
console.log(person1);
function Person(name, age){
this.name = name;
this.age = age;
this.sayHello = function(){
console.log(this.name + 'Hello!');
}
};
var person1 = new Person('michelle', 27);
var person2 = new Person('frank', 36);
var person3 = new Person('demi', 27);
생성자 함수 : 새로 만든 객체에 속할 프로퍼티들을 초기화 하는 역할
function bar(){
this.name = "shinye";
this.age "27";
}
var foo = new bar();
// 이제 foo객체는 다음과 같아진다.
foo = {
name:"shinye",
age:"27"
}
foo.name // "shinye"
1)새로운 빈 객체를 생성
2)"1)"과정으로 만든 빈 객체의 프로토타입을 설정
3)'this'키워드에 "1)"과정에서 생성한 빈 객체를 대입해 생성자 함수를 실행한다.
class Car {
private int currentSpeed;
private int accelerationTime;
...
① public void accelerate(int speed, int second) { // 선언부
// 구현부
System.out.println(second+"초속->시속 "+speed+"로 가속함!!");
}
...
}
class Car {
private int currentSpeed;
private int accelerationTime;
public void accelerate(int speed, int second) {
System.out.println(second + "초간 속도를 시속 " + speed + "로 가속");
}
}
public class Method01 {
public static void main(String[] args) {
Car myCar = new Car(); // 객체 생성
myCar.accelerate(60, 3); // 메소드 호출
}
}
class Data1 {
int value;
}
class Data2 {
int value;
Data2(int x) { // 매개변수가 있는 생성자.
value = x;
}
}
class ConstructorTest {
public static void main(String[] args) {
Data1 d1 = new Data1();
Data2 d2 = new Data2(); //에러가 발생한다.
}
}
class Car {
String color;
String gearType;
int door;
Car() {}
Car(String c, String g, int d) { // 매개변수가 있는 생성자
color = c;
gearType = g;
door = d;
}
}
class CarTest {
public static void main(String[] args) {
Car c1 = new Car();
c1.color = "white";
c1.gearType = "auto";
c1.door = 4;
Car c2 = new Car("white", "auto", 4);
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
}
}
class Car {
String color;
String gearType;
int door;
Car() {
this("white", "auto", 4);
}
Car(String color) {
this(color, "auto", 4);
}
Car(String color, String gearType, int door) {
this.color = color;
this.gearType = gearType;
this.door = door;
}
}
class CarTest2 {
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car("blue");
System.out.println("c1의 color=" + c1.color + ", gearType=" + c1.gearType+ ", door="+c1.door);
System.out.println("c2의 color=" + c2.color + ", gearType=" + c2.gearType+ ", door="+c2.door);
}
}