Relative Content

Tag Archive for constructors

Why is there no default constructor generated if you define an explicit constructor?

class Employee{ String name; int id; //No explicit constructors } Now I can invoke the following statement: Employee e1 = new Employee(); With the above code, the compiler will provide the definition for the constructor Employee(). If I define a single explicit constructor as follows: class Employee{ String name; int id; Employee(String aName){ this.name=aName; } […]

Why is there no default constructor generated if you define an explicit constructor?

class Employee{ String name; int id; //No explicit constructors } Now I can invoke the following statement: Employee e1 = new Employee(); With the above code, the compiler will provide the definition for the constructor Employee(). If I define a single explicit constructor as follows: class Employee{ String name; int id; Employee(String aName){ this.name=aName; } […]

Why is there no default constructor generated if you define an explicit constructor?

class Employee{ String name; int id; //No explicit constructors } Now I can invoke the following statement: Employee e1 = new Employee(); With the above code, the compiler will provide the definition for the constructor Employee(). If I define a single explicit constructor as follows: class Employee{ String name; int id; Employee(String aName){ this.name=aName; } […]

Constructor vs casting operator

I’m programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can easily be converted into one another.
But I’m asking myself, if converting by passing an argument of type B to one of A‘s constructors or by implicitly casting B into A, is preferable. Two code examples to illustrate:

Constructor vs casting operator

I’m programming a library (so I have complete access to all the mentioned classes). Two classes (A and B) are essentially the same and differ only by their implementation, so they can easily be converted into one another.
But I’m asking myself, if converting by passing an argument of type B to one of A‘s constructors or by implicitly casting B into A, is preferable. Two code examples to illustrate: