Why do we need a constructor in OOP? - oop

I am new to OOP. I am still in a learning phase.
Why do we need constructors, When we can initialize the values of the properties (variables) by writing a "Initialize function"?
Basically why do we write a constructor when we can achieve the same results even by writing a function for initializing the variables?

The constructor IS the "Initialize function"
Rather than calling two functions
object = new Class;
object.initialize();
You just call
object = new Class();
The logic inside the constructor can be identical to the logic inside the initialize function, but it's much tidier and avoids you naming your function initialize(), me naming mine initialize_variables(), and someone else naming theirs init_vars()... consistency is useful.
If your constructor is very large, you may still wish to split variable initialisation into a separate function and calling that function from your constructor, but that's a specific exception to the scenario.

So answer is simple
Why do we write Constructor?
Because in C you can write,
int i;
if write like this In above case data type and variable defines if you define like this memory allocated for i variable.So simple here we define class name and variable name(object name) we can create memory allocated for class name.
Example
myClass objectName;
But in C++ new keyword is used for dynamic memory allocation, so this dynamic memory which we can allocate to our class but here my example myClass is our class and we want to allocate to dynamic memory allocated.
So
myClass objectName = new myClass();
and simply constructor is memory allocation for class variable is called the constructor.`

the role of the constructor is to initialize the variables/values.it is the "initialization function".The only reason i find on why we use a constructor instead of a normal function to initialize the variables is to stop different people from using different function names and avoid ambiguity and it is much more easier to use a constructor which is instantiated automatically as soon as the class is run,instead of having to write a separate code for instantiation.this may seem small and like something that doesn't require much work,but only for a very small program,for larger ones the struggle is real.

It is usual to put mandatory things into the constructor and optional ones into the Initialise function.
For example, consider an amplifier that requires a power source so that would be supplied to its constructor. Logically, you may want to turn it on and set its power level but one could argue that you might not want to do that until later. In pseudo-code:
class Amplifier
{
public Amplifier(PowerSource powerSource)
{
// create amplifier...
}
public int PowerLevel;
public void Initialise()
{
// turn on...
}
}
The example, above, is rather puerile but it illustrates the concepts at play. It is always an issue of design, however, and opinions do vary.
Some classes of object, however, will have to perform obvious set-up operations during their construction phase. In these cases, the requirement to have a constructor is very easy to understand. For example, if your object might require a variable amount of memory, the constructor would be a logical place to allocate it and the destructor or finaliser would be a logical place to free it up again.

Even if you don't use constructor it will call implicitly by your language translator whenever you create object.Why?
The reason is that it is used for object initialization means the variable(instance) which we declare inside our class get initialized to their default value.
class Person {
//Class have two parts
//1.Data(instance variable)
//2.Methods(Sub-routine)
String name;
int age;
}
public class Stack{
public static void main(String[] args){
Person person1 = new Person();
System.out.println("Name: "+person1.name);
System.out.println("Age: " + person1.age);
}
}
Output- Name: null
Age: 0
"null" and "0" are default values which are impicitly set by default constructor.

When we initialize a class by creating an instance or object the constructor is called automatically. This is very helpful when we need a huge amount of code to be executed every time we create an object.
The best use of constructor can be seen when we create a " graphical user interface". While building a GUI for an application we need to separate the code for designing the GUI and the business logic of the application. In such a case we can write the code for designing GUI, in a constructor and business logic in respective methods. This make the code tidy and neat too.
Also when an object is created the global variables can be initialized to their default values using constructor. If we don't initialize the global variables, then the compiler will do it implicitly by using the default constructor.
So constructor is a very wise concept which appears to be an idiosyncrasy at first but as you code further and more and more you will realize it's importance.

Because constructors are exactly for that: to avoid using an "initialize function"
Plus you can have have as many constructors as you want: you juste feed them some parameters, depending how you want to inialize your object.

Constructor is a special member function which has same name as class name and called whenever object of that class is created. They are used to initialize data field in object.
Constructor has following properties:
It has same name as class name.
It is called whenever object of a class is created.
It does not have return type not even void.
It can have parameters.
Constructor can be overloaded.
Default constructor is automatically created when compiler does not find any constructor in a class.
Parameterized constructor can call default constructor using this() method.
A constructor can be static for static data field initialization.
It is not implicitly inherited.
For More Info
https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

Related

What is the purpose of explicit getters in kotlin?

Using getters and setters is a very well known practice in object oriented languages. This is done in order to have a greater control on the variables. To achieve this, we make the variables private in java and hence we need both getters and setters there.
But in kotlin this is not the case. Here even public variables are accessed through getters and setters by default. Though setters can be used to validate an assignment to a variable, getters just return the variable as it is stored (and I think this is it for them). Hence custom getters are not required at all.
I have also seen some wrong usage of this feature where instead of writing a zero argument function, they use a val and do the computation in the getter. This creates an illusion that the thing is just a val but in reality it does not store anything and instead it performs a computation every time.
So is there a real need to have a custom getter?
getters just return the variable as it is stored (and I think this is it for them). Hence custom getters are not required at all.
If that was really the case, why have getters at all in Java? One of the goals of encapsulation is to make sure a change in the class doesn't change it's API. It's the same in Kotlin.
I have also seen some wrong usage of this feature where instead of writing a zero argument function, they use a val and do the computation in the getter. This creates an illusion that the thing is just a val but in reality it does not store anything and instead it performs a computation every time.
This is a perfectly valid use case for a custom getter. In Kotlin, one must not assume that using a property is entirely free of overhead. There are many questions to ask yourself when choosing between a property with a getter or a zero-arg function:
Does it describe behavior? Use a function (walk(), build(), etc)
Does it describe state? Use a property (firstName, lastIndex, etc)
Additionally, a property getter should not throw an exception, should be either cheap to calculate or cached on first access, and should return the same result for multiple consecutive executions. Here's examples from the standard library:
ArrayDeque.first() is a function, it throws if deque is empty.
List.lastIndex is a property, it's cheap to calculate.
Lazy<T>.value is a property, the value is computed and cached on first access.
Most delegated properties make use of custom getters.
More reading:
Why use getters and setters/accessors?
Kotlin: should I define Function or Property?
Just some more info. Other than readability, the possibility of defining a custom getter allows you to evolve a class without changing its public members, even if you started with a simple val with no custom getter.
In a language without properties like Java, if you define a public field:
public class Foo {
public final int value;
public Foo(int value) {
this.value = value;
}
}
And then later you want to modify the class to add a feature where it returns negated values if you flip a Boolean, there's no way to do it without breaking code that uses the original version of the class. So you should have used getters and setters to begin with.
But in Kotlin, you can't directly expose a backing field like this, so it's impossible to paint yourself in a corner like you could with a public field in Java. If your original class is like this:
class Foo(val value: Int)
You could modify it like this to add the feature and have no impact on code that already uses the class.
class Foo(private val originalValue: Int) {
var isNegated = false
val value: Int
get() = if (isNegated) -originalValue else originalValue
}

Passing all arguments to class constructor vs passing arguments to member functions

This question is about OOP design.
What are the advantages/disadvantages of passing all arguments to class constructor vs passing arguments to member functions ?
In my case I know all arguments in the beginning of the program and I don't need to change them until the program is over.
In C++ the situation would be something like that (although in my code I need to parse more arguments and the member functions are more complex):
// All arguments in class constructor
Rectangle::Rectangle(float base, float height, string rectColor){
this->area = 0;
this->base = base;
this->height = height;
this->rectColor = rectColor;
}
void Rectangle::calcArea(){
area = base * height;
}
void Rectangle::paintRectangle(){
// use area
// whatever
}
vs
// Arguments in member functions
Rectangle::Rectancle(){
this->area = 0;
}
void Rectangle::calcArea(float base, float height){
area = base * height;
}
void Rectangle::paintRectangle(string rectColor){
// use area
// whatever
}
One strategy that I'm using is: If I need the variable in multiple member functions I make it a class variable. Is that good or the best approach ?
A bad thing about passing everything into constructor is that it would have lots of arguments. And also I wouldn't need to call the class member functions in my main.
Please explain the main principles I should follow.
Benefits for putting arguments in the constructor:
The instance is more completely initialized (no problems with the order of functions to be called to get a 'complete'useful instance.
Benefits for putting arguments to specific functions:
More flexibility, since the functions use variables instead of 'constants' passed to the constructor
The arguments passed to functions tend to belong better to the functions (e.g. for paintRectangle it is logical to pass the color, but if it never change, why making the flexibility to change the color afterwards?)
To prevent too many arguments in the cnstructor
Create a structure to pass the variables
Create a sub class ... if you need more than 5-7 parameters, possibly the responsibility of the class is too big.
Use named arguments (more clearer, but still the same amount of arguments)
In general, make classes as limited as possible, do not make them more flexible than needed UNLESS you know beforehand the functionality is needed at a later stage.
The one of the most important thing about constructors is that they make your OOP code consistent. For any object, it is good approach, if you already know, that someone created with properties need to have to exist.
i.e. Rectangle cannot exist without "height".
Therefore the "minimum parameters constructor" is great advantage. (the minimum required parameters need to have for object, to be usable and for not able to crash, when computing i.e. area)
If you have more parameters, that they are not neccesary, it is good to create more constructors based on what is probably "often use" of your object.

When is a static variable created?

Let's say I have a static variable in a function:
Private Sub SomeFunction()
Static staticVar As String = _myField.Value
End Sub
When, exactly, is the value from _myField assigned to staticVar? Upon the first call to the function? Instantiation of the enclosing class?
The CLR has no support for this construct so the VB.NET compiler emulates it.
Creation first. The variable is lifted to a private field of the class with an unspeakable name that ensures no name collisions can occur. It will be an instance field if the variable is inside an instance method of the class. So will be created when an object of the class is created with the new operator. It will be a Shared field if the method is Shared or is part of a Module. So will be created in the loader heap by the jitter.
Assignment next, the much more involved operation. The language rule is that assignment occurs when code execution lands on the Dim statement for the first time. The term first time is a loaded one. There's an enormous amount of code generated by the compiler inside the method to ensure this is guaranteed. The kind of problems that need to be addressed are threading, recursion and exceptions.
The compiler creates another hidden helper field of type StaticLocalInitFlag at the same scope as the hidden variable field to keep track of initialization state for the variable. The first part of the injected code is a call to Monitor.Enter() to deal with threading. Same thing as SyncLock. The StaticLocalInitFlag serves as the locking object, note how it is a class and not just a Boolean.
Next, Try and Finally statements guard against exceptions. Inside the Try statement, the value of StaticLocalInitFlag.State is checked for 0. This protects against recursion on the same thread. State is then set to 2 to indicate that initialization code is running. Followed by the assignment. Next, State is checked again to see if it is still 2. If it is not then something went drastically wrong and an IncompleteInitialization exception is thrown.
The Finally block then sets the State to 1 to indicate that the variable is initialized. Followed by a call to Monitor.Leave().
Lots of code, 96 bytes of IL for just a simple variable. Use Static only if you don't worry about the cost.
A Static variable is instantiated when it is assigned, obviously.
When that line is run, not before, not after.
Put a breakpoint on it and you'll see.
Static just means that the value will persist between calls.
Shared class/module members are instantiated the first time the class is accessed, before any Shared constructor and before the call, whether that is to the class constructor or some Shared method/property. I think this may be the origin of your confusion. Static local variables, like local statics in c# are not instantiated in this way.
Interesting information from Tim Schmelter, it appears the value is maintained internally using a hidden Shared class level variable that is instantiated like other Shared class level variables but always with the default value.
The effect observed by you the developer is unchanged, apart from some instantiation delay when the class is accessed. This delay should be undetectable in practice.
The VB.NET compiler creates a static (shared in VB.NET) class-level variable to maintain the value of "staticVar". So it's initialized like any other static/shared variable, on the first use of a static field of that class (or when you call this method).
http://weblogs.asp.net/psteele/pages/7717.aspx

Is there any disadvantage of writing a long constructor?

Does it affect the time in loading the application?
or any other issues in doing so?
The question is vague on what "long" means. Here are some possible interpretations:
Interpretation #1: The constructor has many parameters
Constructors with many parameters can lead to poor readability, and better alternatives exist.
Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:
Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...
The telescoping constructor pattern is essentially something like this:
public class Telescope {
final String name;
final int levels;
final boolean isAdjustable;
public Telescope(String name) {
this(name, 5);
}
public Telescope(String name, int levels) {
this(name, levels, false);
}
public Telescope(String name, int levels, boolean isAdjustable) {
this.name = name;
this.levels = levels;
this.isAdjustable = isAdjustable;
}
}
And now you can do any of the following:
new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);
You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.
As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).
Bloch recommends using a builder pattern, which would allow you to write something like this instead:
Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();
Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.
See also
Wikipedia/Builder pattern
Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters (excerpt online)
Related questions
When would you use the Builder Pattern?
Is this a well known design pattern? What is its name?
Interpretation #2: The constructor does a lot of work that costs time
If the work must be done at construction time, then doing it in the constructor or in a helper method doesn't really make too much of a difference. When a constructor delegates work to a helper method, however, make sure that it's not overridable, because that could lead to a lot of problems.
Here's some quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:
There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.
Here's an example to illustrate:
public class ConstructorCallsOverride {
public static void main(String[] args) {
abstract class Base {
Base() { overrideMe(); }
abstract void overrideMe();
}
class Child extends Base {
final int x;
Child(int x) { this.x = x; }
#Override void overrideMe() {
System.out.println(x);
}
}
new Child(42); // prints "0"
}
}
Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.
Interpretation #3: The constructor does a lot of work that can be deferred
The construction of an object can be made faster when some work is deferred to when it's actually needed; this is called lazy initialization. As an example, when a String is constructed, it does not actually compute its hash code. It only does it when the hash code is first required, and then it will cache it (since strings are immutable, this value will not change).
However, consider Effective Java 2nd Edition, Item 71: Use lazy initialization judiciously. Lazy initialization can lead to subtle bugs, and don't always yield improved performance that justifies the added complexity. Do not prematurely optimize.
Constructors are a little special in that an unhandled exception in a constructor may have weird side effects. Without seeing your code I would assume that a long constructor increases the risk of exceptions. I would make the constructor as simple as needed and utilize other methods to do the rest in order to provide better error handling.
The biggest disadvantage is probably the same as writing any other long function -- that it can get complex and difficult to understand.
The rest is going to vary. First of all, length and execution time don't necessarily correlate -- you could have a single line (e.g., function call) that took several seconds to complete (e.g., connect to a server) or lots of code that executed entirely within the CPU and finished quickly.
Startup time would (obviously) only be affected by constructors that were/are invoked during startup. I haven't had an issue with this in any code I've written (at all recently anyway), but I've seen code that did. On some types of embedded systems (for one example) you really want to avoid creating and destroying objects during normal use, so you create almost everything statically during bootup. Once it's running, you can devote all the processor time to getting the real work done.
Constructor is yet another function. You need very long functions called many times to make the program work slow. So if it's only called once it usually won't matter how much code is inside.
It affects the time it takes to construct that object, naturally, but no more than having an empty constructor and calling methods to do that work instead. It has no effect on the application load time
In case of copy constructor if we use donot use reference in that case
it will create an object and call the copy constructor and passing the
value to the copy constructor and each time a new object is created and
each time it will call the copy constructor it goes to infinite and
fill the memory then it display the error message .
if we pass the reference it will not create the new object for storing
the value. and no recursion will take place
I would avoid doing anything in your constructor that isn't absolutely necessary. Initialize your variables in there, and try not to do much else. Additional functionality should reside in separate functions that you call only if you need to.

What are the best practices for determining the tasks of Constructor, Initialization and Reset methods

This is a general OOP question although I am designing in Java. I'm not trying to solve a particular problem, just to think through some design principles.
From my experience I have reached the habit segregating object setup into three phases.
The goal is to minimize: extra work, obfuscated code and crippled extensibility.
Construction
The minimal actions necessary to
create a valid Object, passes an
existence test
Instantiate and initialize only "one time", never to be over-ridden, non variable objects that will not change/vary for the life of the Object
Initialize final members
Essentially a runtime stub
Initialization
Make the Object useful
Instantiate and initialize publicly accessible members
Instantiate and initialize private members that are variable values
Object should now pass external tests with out generating exceptions (assuming code is correct)
Reset
Does not instantiate anything
Assigns default values to all variable public/private members
returns the Object to an exact state
A Toy example:
public class TestObject {
private int priv_a;
private final int priv_b;
private static int priv_c;
private static final int priv_d = 4;
private Integer priv_aI;
private final Integer priv_bI;
private static Integer priv_cI;
private static final Integer priv_dI = 4;
public int pub_a;
public final int pub_b;
public static int pub_c;
public static final int pub_d = 4;
public Integer pub_aI;
public final Integer pub_bI;
public static Integer pub_cI;
public static final Integer pub_dI = 4;
TestObject(){
priv_b = 2;
priv_bI = new Integer(2);
pub_b = 2;
pub_bI = new Integer(2);
}
public void init() {
priv_a = 1;
priv_c = 3;
priv_aI = new Integer(1);
priv_cI = new Integer(3);
pub_a = 1;
pub_c = 3;
pub_aI = new Integer(1);
pub_cI = new Integer(3);
}
public void reset() {
priv_a = 1;
priv_c = 3;
priv_aI = 1;
priv_cI = 3;
pub_a = 1;
pub_c = 3;
pub_aI = 1;
pub_cI = 3;
}
}
I would design my classes in a way so that an "init" method is not required. I think that all methods of a class, and especially public methods, should guarantee that the object is always left in a "valid" state after they complete successfully and no call to other methods is required.
The same holds for constructors. When an object is created, it should be considered initialized and ready to be used (this is what constructors are for and there are numerous tricks to achieve this). Otherwise, the only way that you can safely use it is checking if the object has been initialized in the beginning of every other public method.
I come from a C++ background where the rules are a bit different from Java, but I think these two-stage initialization principles apply in the general case.
Construction
Everything that can be done at construction time should be done at construction time.
Minimize the amount of "badness" that can result from trying to use your object before calling init().
All member variables need a value, even if it's a normally invalid sentry value (e.g., set pointers to null). I think Java will initialize all variables to zero by default, so you need to pick something else if that's a valid number.
Initialization
Initialize those member variables that depend on the existence of other objects. Basically, do the things you couldn't do at construction time.
Ensure your object is now in a complete, ready-to-use state. Consider throwing an exception if it isn't.
Reset
Think long and hard about what state The System will be in when you'd want to call such a function. It may be better to create a new object from scratch, even if that operation seems expensive. Profile your code to find out if that's a problem.
Assuming you got past item 1, consider writing a method to handle the things that both reset() and your constructor need to do. This eases maintenance and avoids code duplication.
Return your object to the same state it was in after init().
Can't say that I've ever used this exact pattern, but I've used similar things to reduce code duplication. For example when you have an object that may be either created via a constructor or from a another object (like a DTO) via a factory method. In that case, I'll often have an internal initializer that populates the properties of the object that is used by both. Can't say that I've ever used a "reset" method, nor do I see a real need for one if all it does is replicate the process of creating a new object.
Lately, I've moved to only using default constructors and using property settors to initialize the object. The new C# syntax that allows to easily do this in a "constructor-like" format makes this every easy to use and I find the need to support parameterized constructors disappearing.
Is there a reason init() and reset() need to be different? It's hard to see in this simple example why the "does not instantiate anything" rule is important.
Beyond that, I think objects should be useful as soon as they're constructed. If there's a reason -- some circular dependency or inheritance issue -- an object has to be "initialized" after construction, I would hide the constructor and the initialization behind a static factory method. (And probably move the initialization code to a separate configurator object for good measure.)
Otherwise you're counting on callers always to call both the constructor and init(), and that's a non-standard pattern. We have some old, too-useful-to-throw-away code here that does that; it's an abstract dialog class, and what happens is, every time someone extends it, they forget to call constructUI() and then they waste 15 minutes wondering why their new dialog is empty.
Interesting. I especially find this construction useful if you have an object that needs to perform IO operations. I do not want anything to perform IO operations direct or indirectly in their constructor. It makes the object a nightmare to use.