COMSATS University Islamabad, Lahore Campus Introduction to Constructors. Continue.. • It’s a special method that is called at the time of object construction/instantiation. • Constructors are generally used to initialize instance attributes. • Constructor name match with class name, they do not return any value. They mostly have ‘public’ access modifier but its not a requirement. • Demo: Initialize id and name of Person object. Introduction to Constructors • If you have deployed a policy on modification, you should call set method from the constructor, to enforce that policy at the time of object construction. • We can change attributes values later too, using set methods or by direct access (depending how you have defined attributes). • To enforce certain attributes are initialized at the time of object construction, make them private and initialize in constructors. Constructor Overloading • We can define multiple constructors inside a class, its called constructor overloading. • By constructor overloading, we let others to create object of our class in multiple ways. • We can call constructors from each others to avoid code duplication. • Demo: Constructor in Person that initialize id and name. Another that initialize id only. Method Overloading • Its not only the constructors that can be overloaded. We can defined multiple methods of same name in a class but they must be different by: • Number of parameters • Type of parameters • Order of parameters • The return type of such method is kept same, generally* Default Constructor • Its not mandatory do define constructors in a class, when we don’t define a constructor, compiler automatically provide default constructor. • Default constructor is no-argument constructor. • Default constructor is not provided when we define a custom constructor. If you want to create an object passing no arguments, we must define a no-argument constructor. • When we do not add no-argument constructor ourselves, actually we are enforcing a policy to create an object that must pass the asked data. Initializing attributes in Constructor • Generally no-argument constructor have empty body, but its not mandatory. You can initialize attributes inside constructor: for example: public Player(){ this.luckyNumber = new Random().nextInt(10); } • Its not mandatory to initialize only those attributes that object has received in constructor parameters. You can initialize others attributes too, when needed.