Constructor and toString

Download Report

Transcript Constructor and toString

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)
When an object is created, one of the constructor method in
the class must 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
Example
Using constructors
• A constructor method is invoked by the new operation
• Which constructor 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
Example
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 one constructor
method inside the class definition
At least one constructor method in
each Java class (2)
• IF the class definition does not contain any constructor
method:
The Java compiler will automatically add the
following constructor method to the class definition:
At least one constructor method in
each Java class (3)
Creating an object using values
given inside another object
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
Example
object ⇒ String conversion (1)
• Translating an expression containing the + operator by
the Java compiler:
object ⇒ String conversion (2)