150 likes | 171 Views
Constructor and toString. Constructor (1). Constructor method = an instance method (defined inside some class ) that is invoked when an object of that class is created (by the new operation)
E N D
Constructor (1) Constructor method = an instance method (defined inside some class) that is invoked when an object of that class is created (by the new operation) When an object is created, one of the constructor method in the classmust be invoked
Constructor (2) Constructor methods are used to initialize the instance variables inside the newly created object • has the same name as that class • does not have a return type • is often defined using the public access specifier
Using constructors • A constructor method is invoked by the new operation • Whichconstructor method will be invoked depends on the number and type of parameters specified in the new operation • Java compiler may search for a suitable constructor through widening conversion (casting) operations
At least one constructor method in each Java class (1) • Exactly one of the (possibly many) constructor methods defined inside the class must be invoked Every class definition must contain at least oneconstructor method inside the class definition
At least one constructor method in each Java class (2) • IF the class definitiondoes not containanyconstructor method: The Java compiler will automatically add the following constructor methodto the class definition:
Use Case: Copy constructor • Copy constructor = a constructor of a class that uses an object of the same class and creates an (exact) copy of the object.
Automatic conversion of variables of a user-defined type to String When the + operator is used between a object and a string The object referred to by the object reference variable is automatically converted to a string
object ⇒ String conversion (1) • Translating an expression containing the + operator by the Java compiler: