120 likes | 282 Views
Day 20. 5.5 Constructors. When you create an object for a class, you often want certain initializing actions performed, such as giving values to the instance variables.
E N D
Day 20 5.5 Constructors
When you create an object for a class, you often want certain initializing actions performed, such as giving values to the instance variables.
When you create an object for a class, you often want certain initializing actions performed, such as giving values to the instance variables. • A constructor is a special kind of method that is designed to perform such initializations.
Until now, we have created new objects in the manner illustrated by the following example: Pet goodScout = new Pet(); This creates an object whose initial values have no values at all.
To make things even more efficient and faster, we use constructors. • A constructor is a method that is called when a new object is created. It can perform any action you write into its definition, but a constructor is meant to perform initializing actions.
Unlike set methods, constructors are called almost automatically whenever you create an object using the new operator.
Example In the first file, you can write the first method as public PetRecord(String initialName, intinitialAge, double initialWeight){ … }
Different Scenarios • When an object is created, a person may initialize some, all, or none of the instance variables. So we make constructors for reasonable scenarios.
Different Scenarios • So we make constructors for reasonable scenario:Notice: these are not void methodspublic PetRecord() // default constructorpublic PetRecord(String initialName)public PetRecord(intinitialAge)public PetRecord(double initialWeight)public PetRecord(String initialName, intinitialAge, double initialWeight)
Write Code (first file) PetRecord- name: String- age: int- weight: double + writeOutput: void+ PetRecord(String iName, intiAge, double iWeight)+ PetRecord(String iName)+ PetRecord(intiAge)+ PetRecord(double iWeight)+ PetRecord()+ set(String nName, intnAge, double nWeight): void+ set(String nName): void+ set(intnAge): void+ set(double nWeight): void
Write Code (first file) + set(String nName, intnAge, double nWeight): void+ set(String nName): void+ set(intnAge): void+ set(double nWeight): void+ getName: String+ getAge: int+ getWeight: double
At Home, do homework on WIki • Right now ... We gotta do some JavaScript Web Development