Constructor OA special method automatically called when an object is created by new() o Java provide a default one that takes no arguments and perform no special initialization OInitialization is guaranteed OAll fields set to default values:primitive types to 0 and false,reference to null
Constructor lA special method automatically called when an object is created by new() lJava provide a default one that takes no arguments and perform no special initialization ¡Initialization is guaranteed ¡All fields set to default values: primitive types to 0 and false, reference to null
Constructor (cont. o Must have the same name as the class name OSo the compiler know which method to call o Perform any necessary initialization Format:public ClassName(para)f...} No return type,even no void! OIt actually return current object o Notice:if you define any constructor,with parameters or not,Java will not create the default one for you
Constructor (cont.) lMust have the same name as the class name ¡So the compiler know which method to call l Perform any necessary initialization l Format: public ClassName(para){…} l No return type, even no void! ¡It actually return current object l Notice: if you define any constructor, with parameters or not, Java will not create the default one for you
Constructor example class Circlef double r; public static void main(String[]args){ Circle c2 new Circle();/OK,default constructor Circle c new Circle(2.0);//error!! }
Constructor example class Circle{ double r; public static void main(String[] args){ Circle c2 = new Circle(); // OK, default constructor Circle c = new Circle(2.0); //error!! } }
Constructor example class Circlef double r; public Circle(double r){ this.r r;//same name! } public static void main(String[]args){ Circle c=new Circle(2.0);//OK Circle c2 new Circle();//error!!,no more default Circle.java:8:cannot resolve symbol symbol constructor Circle ( location:class Circle Circle c2 new Circle();//error!! 1 error
Constructor example class Circle{ double r; public Circle (double r) { this.r = r; //same name! } public static void main(String[] args){ Circle c = new Circle(2.0); //OK Circle c2 = new Circle(); //error!!, no more default } } Circle.java:8: cannot resolve symbol symbol : constructor Circle () location: class Circle Circle c2 = new Circle(); //error!! ^ 1 error