Time t = new Time();
t.hour = 12;
t.minute = 34;
t.second = 56;
Add constructor : To initialize instance(iv group) easily.
Time t = new Time(12,34,56);
class Car {
String color;
String gearType;
int door;
Car() {}//default constructor
Car(String c, String g, ind d) {
//iv group
color = c;
gearType = g;
door = d;
}
}
//1.declare reference type variable
//2.create object using operator new
//3.initialize with calling constructor
Car c = new Car("white","auto",4);
constructor name = class name
no return value.(no void)
All class must have more than one constructor.
class Card {
...
//overlading...
Card() {//default constructor
//Initialize instance
}
Card(String kind, int number) {
//Initialize instance
}
}
constructor type
default constructor
no parameter
when there is no constructor, compiler adds automatically.
class Data_1 {//there is no constructor so compiler adds automatically.
int value;
//Data_1(){}
}
class Data_2 {//there is one constructor.
int value;
//MUST include default constructor manually
Data_2() {}
Data_2(int x) {
value = x;
}
}
class Ex6_11 {
public static void main(String[] args) {
Data_1 d1 = new Data_1();//call constructor;
Data_2 d2 = new Data_2();//call default constructor=>error.cannot resolve symbol : issue with name
//must add default constructor in Data_2!
}
}
main class and other method class can be separated like above?