Task: Parameterized Constructor
A constructor is a special type of method which is used to initialize the attributes of objects.
Our account program only works because Java initializes the property balance with the built-in default constructor to 0 when creating the objects.
In e.g. C++ this would not work, balance would not have a defined initial value. Its initial value depends on random combination of bits in memory!
Account account1 = new Account(); // Creation of object of the class Account // using the default constructor
The so-called default constructor has no parameters.
But even if an account with e.g. € 50 starting credit is to be generated, then a parameterized constructor has an advantage. The amount of the start credit is then passed as an argument in the object creation with:
Account account2 = new Account(50); // an argument is passed // to the parameterized constructor
This functionality has to be implemented:
1 public class Account { 2 private float balance; 3 4 Account(float initialCredit) { // Definition of parameterized constructor 5 balance = initialCredit; 6 } 7 ...
An empty account can now be created with:
Account account3 = new Account(0); // creation of an empty account
But the default constructor no longer exists!
Not possible anymore:
Account account1 = newAccount();// Creation of object of the class Account using // the default constructor not possible yet
If the functionality is still required, a no-arg constructor must be defined in addition:
1 public class Account { 2 private float balance; 3 4 Account() { // Definition of no-arg constructor 5 balance = 0; 6 } 7 Account(float initialCredit) { // Definition of parameterized constructor 8 balance = initialCredit; 9 } 10 ...
Note:
- Constructors have the same identifier in Java as the class itself.
- Constructors have no return value, also no "void".
(Only in Java there is the possibility of additional definition of static and instance initializers, which are not considered here for now.)
__________________________________________________________________________________________________
Task: Realize the following UML class and object diagram in Java code.
UML class diagramm and associated object diagramm
The accountNumber should be automatically incremented by the constructor.
Realize this with the help of a static class-wide variable cntAccountNo.