Initialization Blocks:
Blank initialization blocks:
Why we need these as already we have constructors to initialize variables?
With constructors we can take user input and set it to class variables then initialize the
values, but with the blocks we can’t do.
These are not shared with all the instances.
We can have multiple initialization blocks
Static initialization blocks:
These are shared with all the instances (one copy)
Can’t take user inputs
Static Initialization blocks called first when all blocks are present
Order of executing the blocks:
1. Static Initialization block
2. Blank Initialization block
3. Constructors
public class Blocks {
//Initialization block 1
[Link]('Initialization block 1 is called');
//Initialization block 2
[Link]('Initialization block 2 is called');
//static Initialization block 1
Static {
[Link]('Static Initialization block 1 is called');
//static Initialization block 2
Static {
[Link]('Static Initialization block 2 is called');
//blank constructor
public Blocks(){
[Link]('Blank constructor is called');
//Parameterized constructor to set class value
public Blocks(Integer recoveredInArea){
this();
[Link]('Parameterized constructor is called');
}
Inner Class:
Inner class is used to logically group the classes together
When a class is supposed to be used by one single class
public class Company {
public String companyName;
public String ceo;
public Integer employeeCount;
public Long revenue;
// List of all customers
// add new customer
// print the list of all customers
// private inner class to store customer information
}
/** * Company Class Stores information about the company and its customers * */
public class Company {
public String companyName;
public String ceo;
public Integer employeeCount;
public Long revenue;
// List of all customers
private List<Client> customers = new List<Client>();
// add new customer
public void addNewCustomer(String name, String website, String email, Long phone) {
Client customer = new Client(name, website, email, phone);
[Link](customer);
}
// print the list of all customers
public void getAllCustomers(){
for(Client customer : customers){
[Link]('Customer Name: '+[Link]+', Website: '+[Link]+',
Phone: '+[Link]+', Email: '+[Link]);
}
}
// private inner class to store customer information
private class Client {
public String clientName;
public String website;
public String email;
public Long phone;
Client (String clientName, String website, String email, Long phone){
[Link] = clientName;
[Link] = website;
[Link] = email;
[Link] = phone;
}
}
}
------------------------------------- dev console ------------------------------
Company companyeg = new Company();
[Link] = 'Google Academy';
[Link] = 'Sundar P';
[Link] = 6;
[Link] = 1000000;
[Link]('ABC Infotech', '[Link]', 'abcinfotech@[Link]',
7778889990L);
[Link]('Foodpanda', '[Link]', 'foodpanda@[Link]',
7778889990L);
[Link]('XYZ Infotech', '[Link]', 'xyzinfotech@[Link]',
6668889990L);
[Link]();