1 / 15

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)

donaldgil
Download Presentation

Constructor and toString

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Constructor and toString

  2. 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

  3. 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

  4. Example

  5. 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

  6. Example

  7. 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

  8. 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:

  9. At least one constructor method in each Java class (3)

  10. Creating an object using values given inside another object

  11. 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.

  12. 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

  13. Example

  14. object ⇒ String conversion (1) • Translating an expression containing the + operator by the Java compiler:

  15. object ⇒ String conversion (2)

More Related