Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Constructor Chaining [duplicate]

Hi I am just learning about constructor chaining in Java and had some questions...

  1. First of all could someone please explain when I would ever need to use this? Off the top of my head I seriously cannot think of a situation.

  2. In this example, within the constructor with no arguments I call another constructor. How do I access this new "James Bond" object for future use?

    import java.util.*;
    
    class Employee
    {   
        private String name;
        private double salary;
    
        public Employee()
        {
            this("James Bond", 34000);
        }
    
        public Employee(String n, double s)
        {
            name = n;
            salary = s;
        }
    
        public String getName()
        {
            return name;
        }
    
        public double getSalary()
        {
            return salary;
        }
    
        public static void main(String[] args)
        {
            Employee a = new Employee();
        }
    }
    
like image 863
jimbo123 Avatar asked Dec 11 '22 13:12

jimbo123


1 Answers

Actually I believe the most common use of chained Constructors is when the Constructor does more than just setting the member variables.

static int numOfExamples = 0;
public Example(String name, int num)
{
    this.name = name;
    this.num = num;
    numOfExamples++;
    System.out.println("Constructor called.");
    Log.info("Constructor called");
}

public Example()
{
    this("James Bond",3);
}

That way we don't have to write the code for logging and incrementing the static variable twice, instead just chaining the constructors.

like image 132
Adrian Jandl Avatar answered Jan 02 '23 05:01

Adrian Jandl