I believe I understand what constructors are now, but to me it seems they are just used for passing info to methods in another class. So why not just call a method and supply a parameter instead? Have I got this wrong?
Constructors are used to create objects and are not ordinary methods. Whenever you use new to create an object, you actually call a constructor. For example:
new MyClass(); //here MyClass() is a constructor with no params
Note:
Constructor declarations look like method declarations—except that
they use the name of the class and have no return type
If I understand it right:
Constructors are always called, so these attributes MUST BE passed. If you pass this info through methods they don't have to be passed, so they could be missing.
Constructors are used to initialize new instance of an object, whenever you pass parameters or not.
Having parameters in a constructor is just a way to make it easy to set some initial attributes during the object initialization, which the object will most probably need in order to work as expected.
However, if those attributes weren't needed to be initialized for the correct operation of the instance object, it would make more sense not to pass them to the constructor, but just having some setters to pass them at any other time you need.
Related
I am very new to java and I was just trying to get acclimatised to the syntax and there is one thing that I have been confused about. What is the difference between instantiating a new object in java then using the setname method to name it, and using a string parameter to assign a name in the constructor.
So if I have a class called Dog, what is the difference between,
naming the dog by passing a name parameter onto its constructor and using setname under it. Are these processes different.
Yes these are two differents things.
You have to think about what exactly is your object and how he relates to his properties.
Constructor let you initialize the class variables dynamically at the time of instantiating the class so you should put the parameters without which the object would not be what it is (In the context of your code)
The setters methods are a totally different thing, it let you access variable to modify it.
You should have setters when ,in your code, it make sense to modify a private variable.
If having a Dog without a name does not make sense in your code then add it as parameter in constructor.
Can a Dog be renamed ? if yes, then add a setName method.
Does your Dog have a default run speed that you can modify ? Then add a default speed variable in the class and setSpeed method.
Constructor are for parameters that make an object what it is and parameters that you always want to define when instanciating the object.
Setters are for modifying parameters after object was created.
I want to safe guard my method parameters that were passed to the called method from being changed accidentally. I know that we can use final keyword to achieve this (partially) like the following in the method signature.
public void someMethod(final int intVal, final MyClass myobj){}
With the help of the above signature I cannot change the value of intVal, but however I can change the values (members) of myobj (I can safe guard only the reference not being changed, but not the members of the referencing object, that why I said partial).
Now I am looking to safe guard my myobj members either, getting changed in the called method someMethod.
In my knowledge I could achieve this using the following ways
Create an immutable class and pass it as a parameter
Deep copy the object and send the cloned object to the method.
Is there any better apporach to safeguard the method parameters?
Why we instantiate some object inside constructor and some outside. What are the advantage/ disadvantages of doing this.
public class HomePage_Util {
private Common_Functions cfObj = new Common_Functions();
HomePage_OR home_ORobj;
Logging logObj = new Logger();
public static String scptName;
public ArrayList<String> homeScriptMsgList = new ArrayList<String>();
public HomePage_Util(WebDriver driver) {
home_ORobj = new HomePage_OR();
PageFactory.initElements(driver, home_ORobj);
}
Objects are initialized in constructors only when they are needed to initialize other objects in a sequence. Like in your example first of all the object i.e. home_ORobj = new HomePage_OR(); will be created as this object is needed to initialize the PageFactory elements in next step.
So if home_ORobj = new HomePage_OR(); is not needed to initialize the PageFactory elements then you could write it out of the constructor i.e. globally.
Code reuse is the main advantage of initializing elements in a constructor. Also initializing few things makes sense only when the object is created or constructor is called.
Constructor is basically for creating a new object of a class. When you create an object, a copy of all variable for that object is created and assigned default value.
The purpose of initiating some variables in constructor is to assigned the value at the time of creation of an object. So that you don't have to assigned value implicitly.
My guess is the writer of such code wasn't sure if home_ORobj would be initialized before the call to initElements() but the ones outside are initialized first so it doesn't matter.
Though if they depend on each other (i.e. use another in the parameters to the constructor) it's good to put them in the constructor as code formatters may re-order the list of elements breaking the the code.
Some objects requires few fields to be initialised in order to correctly construct that object before it being used. Constructor is called when the object is getting created, hence it is initialised in constructor.
You can have overloaded constructor with different initialistion for different scenarios.
You can always have a method called initializeValues and call it after you create an object rather than putting it in constructor.
Putting it in constructors will ensure that it is always called when you create an object.
Super class constructor is always called before the derived class constructor, so it makes sense.
One advantage is to avoid a static block to initialize static members.
AFAIK It's not exactly the same in the lifecycle of an object : constructor is executed after the firsts initializations.
An instance field that is initiated outside a constructor is always going to be that way initially when a new object is created - for every instance. The ones initiated in a constructor may have some special meaning for the new instance such as the WebDriver in your example seems to have so it cannot be initiated elsewhere. A constructor that requires an instance of certain type to be passed as an argument does enforce design since it cannot be passed anything else and cannot be constructed without it.
A class may contain multiple constructors that may behave differently and instantiate different fields and leave others untouched (like when there are multiple purposes for a class, which actually may indicate bad design).
Additionally, if a class does not have a default constructor => upon deserialization no constructor's get called.
As per standard book constructor is a special type of function which is used to initialize objects.As constructor is defined as a function and inside class function can have only two type either static or non static.My doubt is what constructor is ?
1.)As constructor is called without object so it must be static
Test test =new Test();//Test() is being called without object
so must be static
My doubt is if constructor is static method then how can we frequently used this inside
constructor
Test(){
System.out.println(this);
}
Does the output Test#12aw212 mean constructors are non-static?
Your second example hits the spot. this reference is available in the constructor, which means constructor is executed against some object - the one that is currently being created.
In principle when you create a new object (by using new operator), JVM will allocate some memory for it and then call a constructor on that newly created object. Also JVM makes sure that no other method is called before the constructor (that's what makes it special).
Actually, on machine level, constructor is a function with one special, implicit this parameter. This special parameter (passed by the runtime) makes the difference between object and static methods. In other words:
foo.bar(42);
is translated to:
bar(foo, 42);
where first parameter is named this. On the other hand static methods are called as-is:
Foo.bar(42);
translates to:
bar(42);
Foo here is just a namespace existing barely in the source code.
Constructors are non-static. Every method first parameter is implicit this (except static) and constructor is one of that.
Constructors are NOT static functions. When you do Test test =new Test(); a new Test object is created and then the constructor is called on that object (I mean this points to the newly created object).
The new keyword here is the trick. You're correct in noting that in general, if you're calling it without an object, a method is static. However in this special case (i.e., preceded by the new keyword) the compiler knows to call the constructor.
The new operator returns a reference to the object it created.
new Test(); // creates an instance.
The System.out.println(this); is called after the new operator has instantiated the object
Not static. Read about constructors http://www.javaworld.com/jw-10-2000/jw-1013-constructors.html.
Neither.
Methods can be divided into 2 types: static/non-static methods, aka class/instance methods.
But constructors are not methods.
When we talk about static class then it comes to our mind that methods are called with class name,But in case of constructor ,Constructor is initialized when object is created So this proves to be non-static.
Constructors are neither static (as called using class name) or non-static as executed while creating an object.
Static:
Temp t= new Temp();
The new operator creates memory in the heap area and passes it to the constructor as Temp(this) implicitly. It then initializes a non-static instance variable defined in a class called this to the local parameter variable this.
Below example is just for understanding the concept, if someone tries to compile it, it will give the compile-time error.
class Temp{
int a;
Temp this; //inserted by compiler.
Temp(Temp this){ //passed by compiler
this.this=this; // initialise this instance variable here.
this.a=10;//when we write only a=10; and all the non-static member access by this implicitly.
return this; // so that we can't return any value from constructor.
}
}
Constructor is static because:
It is helping to create object.
It is called without object.
Constructor is used to initialize the object and has the behavior of non-static methods,as non-static methods belong to objects so as constructor also and its invoked by the JVM to initialize the objects with the reference of object,created by new operator
If I do this in Java to call a method name from a class dynamically, it works.
MainApp app = new MainApp();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
//call method
meth.invoke(app, new MyParameterType("hello"));
But this worked because I know the constructor in the invoke method. But if I were to pass the Method object as a parameter to some other classes, and I don't know who is the constructor, I cannot invoke the method any more. Even if I know, I may not want to create a different object to just make a call to the method. For eg:
//This is in the class call MainApp.java.
//There is a method in MainApp.java that looks this way: myMethod(MyParameterType param);
MainApp app = new MainApp();
OtherClass myClass = new OtherClass();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
myClass.callMe(meth);
//Inside OtherClass.java
public void callMe(Method meth) {
//call method
meth.invoke(########, new MyParameterType("hello"));
}
In this case, what should I put for the ######## parameter? Within the context of OtherClass.java, the base constructor object wouldn't be known. And why would I need if since meth is already a Method type that I just call like a function?
Thanks
Assuming it's an instance method, you've got to have an instance to call the method on, just like anything else. How you get hold of that instance will depend on what you're trying to do; you could pass in a Constructor, or a reference to an existing object, or some interface which will create the instance when you ask it to... we can't really give you any advice on which approach is the most suitable without knowing what you're trying to do.
If it's a static method, you can pass null for the first argument.
What it seems you are looking for or thinking about is the concept of `lambda functions``. Those can be called in isolation.
A Method type is not a standalone method, but more like a 'path' into an object. Compare this with a relative URL like /subscribe.html. Out of context this is pretty useless, but when bundled with a site like www.example.com it makes sense.
As such, Method can only be used in combination with an instance. (edit: as John mentioned, unless it's a static method of course which do not need instances)
If you can safely invoke a method without providing an instance, it should be a static method, in which case any instance provided is ignored, you can give it null.
If you have to provide an instance of the object, there is no way around this.
If the developer who write the method has labelled it non-static incorrectly, I suggest you discuss with them why they did it.