/ W3SCHOOLS

W3schools - Constructor

이 페이지는 다음에 대한 공부 기록입니다
Lecture에서 배웠던 내용을 복습하며 작성했습니다

찾으시는 정보가 있으시다면
주제별reference를 이용하시거나
우측 상단에 있는 검색기능을 이용해주세요

Constructors

Is a special method that is used to initialize objects.

The constructor is called when an object of a class is called it can be used to set initial values for object attributes

Constructor name must match the class name, and can’t have a return type

All classes have constructors by default(if you do not create a class constructor yourself, java creates one for you, then, you are not able to set initial values for object attributes

public class Main{
  int x;
  public Main(){
    x = 5;
  }
  public static void main(String[] args){
    Main myObj = new Main();
    System.out.println(myObj.x);		// output 5
  }
}

Parameters(Constructor)

Can also take parameters, which is used to initialize attrubutes

public class Main{
  int modelYear;
  String modelName;

  public Main(int year, String name){
    modelYear = year;
    modelName = name;
  }

  public static void main(String[] args){
    Main myCar = new Main(1969, "Mustang");
    System.out.println(myCar.modelYear + " " + myCar.modelName); //output 1969 Mustang
  }
}