Given this code:
public class Example
{
public Example(String name)
{
input = name;
}
public someMethod()
{
//some code
}
}
In java when you declare a new (object or instance) as such:
Example foo = new Example("jo");
what is actually happening here?
my question is:
is a new object being created with the parameter of the class constructor?
will the new object have all of the arguments of the constructor and data members within the braces?
Given your code that does not have a default constructor
the line Example foo = new Example(); will result in compilation error
The default constructor is defined by default unless you add another constructor with argument(s). In this case you have to explicitly define the default constructor otherwise you can only create instance with the constructor that takes argument(s)
This will not compile. Java will automatically define a constructor for you if you don't include one. It will not include parameters. So if you took the public Example piece out of your code, or added in a no argument constructor Java would compile it.
Your code won't compile as you created a constructor and then tried to instantiate an object of the class without giving it any attributes (causing a compile error).
Additionally, it is worth pointing out that your code wouldn't work anyway as the input you use isn't defined anywhere. It should be defined before the public Example like so:
String input;
If you did this and DIDN'T specify a constructor (i.e. let Java create it for you), Java would hold the value "null" for input.
Any instance variables that are declared public and belong to the class will be accessible by the object you create.
Edit: Now you have altered your code to include the passing of an argument, it will compile provided you declare the String input as in my answer in the class.
As Rohit said you will have a compiler error as no default ctor is specified.
However, assuming you did have a default ctor: what happens is the data members are created, that is, memory is allocated for each non static instance member.
If the class extends any class, the constructor (parent's ctor) should be invoked before the subclass's constructor body executes, and then the constructor body initializes data members using local variables or local variables that are passed as ctor arguments.
If the constructor body executes to a completion, that is no exceptions, it returns a reference to the newly created object.
So:
new creates the object and returns the reference of that object if everything went well.
Constructors only initialize data. Using data defined in the
constructor body, or from arguments supplied by the constructor
caller. Those arguments don't create an object, they supply data
that may be useful to an object.
Related
A constructor is used to initialize a value and assign it to the class variable in the time of creating the class instance, right?
public class Joke{
private String jokeSetup;
private String jokePunchLine;
public Joke(String jokeSetup , String jokePunchLine){
this.jokeSetup=jokeSetup;
this.jokePunchLine=jokePunchLine;
}
}
Consider the following:
public Joke(String jokeSetup , String jokePunchLine)
Is another variable with same name created?
If so, why are they assigned to the former jokeSetup and jokePunchLine values?
PS:This code is not created by me.It was shown in the videos from which I am learning Java.
The purpose of a constructor is to initialize the object that was just created, for instance by filling in its instance fields (also called instance variables). this is used in your constructor to refer to the instance the constructor is initializing.
In your example constructor, you have parameters and instance fields. The constructor is taking the values of the parameters and assigning those values to the instance fields:
public Joke(String jokeSetup , String jokePunchLine)
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---- Declares parameters this
// constructor accepts when
// called
{
// vvvvvvvvv------------ parameter
this.jokeSetup=jokeSetup;
// ^^^^^^^^^^^^^^---------------------- instance field
// vvvvvvvvvvvvv---- parameter
this.jokePunchLine=jokePunchLine;
// ^^^^^^^^^^^^^^^^^^------------------ instance field
}
The constructor could initialize instance fields with constant values instead, or by using a parameter value indirectly (for instance, looking something up), etc. It's not always a direct one-to-one assignment as it is in your example.
In your example, the parameters have the same names as the instance fields, but that's not a requirement. For instance, this constructor does exactly the same thing as yours:
public Joke(String theJokeSetup , String theJokePunchLine)
// ^---------------------^---------- Note the name changes
{
// vvvvvvvvvvvv------------ parameter
this.jokeSetup = theJokeSetup;
// ^^^^^^^^^^^^^^--------------------------- instance field
// vvvvvvvvvvvvvvvv---- parameter
this.jokePunchLine = theJokePunchLine;
// ^^^^^^^^^^^^^^^^^^----------------------- instance field
}
Java lets you leave off the this. part when referring to an instance field and just use the field name on its own (e.g. jokeSetup instead of this.jokeSetup). You can't do that in your constructor unless you rename the parameters, though, because they have the same names as the instance fields, so jokeSetup in your constructor is the parameter, not the field. When there's a conflict like that, the most local identifier takes precedence (in your constructor, the parameter is the most local).
When there's no conflict, it's a matter of style whether you use the this. part or not. (I always use this., I find it clearer.) So for instance, here's another version of that constructor which does exactly the same thing as your original:
public Joke(String theJokeSetup , String theJokePunchLine)
// ^---------------------^---------- Note the name changes
{
// vvvvvvvvvvvv------------ parameter
jokeSetup = theJokeSetup;
// ^^^^^^^^^--------------------------- instance field
// vvvvvvvvvvvvvvvv---- parameter
jokePunchLine = theJokePunchLine;
// ^^^^^^^^^^^^^----------------------- instance field
}
I mention this because, again, when there's no conflict, it's a matter of style, and you'll see this style used sometimes.
The class has a field named jokeSetup.
The method has a parameter of the same name that shadows that field.
So in essence there are two variables with the same name.
Using this makes it possible to again differentiate the two different usages of the same name, as this.whatever always denotes the corresponding field.
And you nailed it: shadowing is actually not a good idea. But this "pattern" is actually very common in Java. You could avoid it by giving the parameter a different name, such as _jokeSetup, but deviating from common practices is also bad practice.
A parametrized constructor can be used to initialize value to the variables in the time of creating it. When the parameters and variable names are same then in this case to differentiate between both, we use this keyword. This keyworord always refer to local variable of the method or class.
Java has an implied context for symbol names; the class instance (ie this) for non-static contexts and the class (eg Joke) for static.
This lets you omit the context when there is no conflict for the symbol name. For example
public String getJokeSetup() {
return jokeSetup; // no "this." required, it's implied
}
When there is a conflict for the name such as the case with a method argument named the same as a field, you need to explicitly define the context, eg
public void setJokeSetup(final String jokeSetup) {
// you must prefix the field with "this." to differentiate it from the argument
this.jokeSetup = jokeSetup;
}
Finally, here's an example that avoids a symbol name conflict
public void setJokeSetup(final String js) {
jokeSetup = js;
}
It is fairly typical to name arguments the same as the fields they correspond to but you're certainly not constricted to such a convention.
I have read in many sources and books that constructor is used to initialise the fields when an object is created. I have also read that JVM provides a default constructor if I don't mention one. What is the purpose of a constructor if it is not required to initialise the fields like the one I have mentioned below?
I also understand that a constructor without parameter is required as
it is necessary during object creation when an argument is not passed
(when programmer-defined constructors with parameters exists).
Is it necessary for JVM to provide a constructor which is actually not required?
public class test {
int a;
public test() {
//this constructor is useless
}
public static void main(String[] args)
{
test ob= new test();
System.out.println(ob.a);
//this prints 0 which means a constructor is not required in intialising `a`
}
}
A constructor like test() makes sense if the programmer defines it since there could be other constructors which takes argument.
But why is it necessary for JVM to provide one when no constructor is declared by the programmer?
I have already tested and proved that initialising a field doesn't require constructor.
Also what does the default constructor look like?
The problem is that while you know the default constructor doesn't do anything in this example, in future the constructor might do something even if you don't realise it is and you might not be able to re-compile everywhere the code is used reliably. So the safest, simplest thing to do is to always call a constructor which might change in the future and let the JIT optimise away the constructor if it doesn't actually do anything.
The byte code always calls a contructor, whether you provide one or not. When you compile code which uses the default constructor it cannot assume the constructor doesn't do anything useful as you can add something to it later to do something useful. e.g.
Say you change
public class Test {
int a;
// public Test() { //this constructor does nothing
}
to
public class Test {
int a;
final List<String> strings = new ArrayList<>();
// public Test() { //this constructor does something now.
}
or
public class ServerTest {
final List<String> strings = new ArrayList<>();
}
public class Test extends SuperTest {
int a;
// the default constructor has to call super();
}
The constructor now initialised the strings field. You can change this class without having to re-compile everywhere it is used and say, hey, my constructor now does something useful, you should call it now.
The reason the JVM adds a default constructor if you haven't provided one is down to inheritance. Say for example you have 3 classes (A, B & C) in which B extends A and C extends B. Now when you instantiate C it will call the constructor of C and also the constructors of B and A. If a constructor was missing in one or more of these classes then the instantiation would fail. So having the compiler automatically add a default constructor avoids error like this. You may not need to actually do any work in your constructor, but it's required for the JVM to instantiate the object.
The constructor(s) (both default and custom one(s)) is not only used to initialize the fields of an object but also to initialize the object itself even if it has no fields at all. Calling the constructor, JVM allocates memory for this object and creates its reference.
It is the compiler, and not JVM, who inserts a default constructor on absence.
A default constructor is needed because the constructor of the base class needs to be called from a constructor.
The default constructor looks like:
public Test() {
super();
}
Here while you are creating the object new test(),
here parenthesis states the default constructor of object test.After creating the object,if you didnot give any constructor the default constructor is constructed by jvm.so after construction of your object first call goes to your default constructor.
The default constructor is a no argument constructor called automatically by the compiler when you haven't defined any constructor. Anyway, a constructor as the one you defined, can be also called a default constructor.
It basically calls the superclass' constructor making use of the super() method.
So the default constructor called automatically would be something like:
public ClassName(){
super();
}
Java's Compiler creates a Default Constructor if no other constructor is defined for the class.
But why?
The compiler's job is to chain the Subclass's constructor to the Super Class(ultimately Object class). It's not the Compiler's work to give a default constructor to your class therefore Java is doing it for you.
To do the chaining, it first checks if there is any constructor in the class, if yes it will add super() to that constructor.
If there is no constructor idefined in the class in order for the compiler to do a proper chaining, Java adds a default constructor and a call to super() into it.
Why ?
Because every class is a subclass of an Object class (directly or indirectly), it will inherit an object class, to do so the said Object class must be fully initialised. This is done by the default constructor.
As we know Java is an object oriented language. Everything is objects in Java. We also know that objects have something (instance variables / fields) and do something (methods). Its safe that we change the state of instance variables using methods i.e; setters & getters. So in a constructor we initialize the instance variables. So in other words constructor is doing something for an object. So isn't it correct to presume that constructor is kind of a utility method just like a setter which sets value? The difference is in case of a setter even we have return type void and in constructor we don't have any return type. And setters can be called any number of times on an object but constructor can be called once in a lifetime of an object.
Can we say Contructors are Methods in Java?
If you're new to Java and trying to grasp the concept for the first time, you can think of constructors as factory methods. (Like in Python for instance where a constructor just a method called __init__.) You should however move on quickly and understand that there are many differences. To name a few:
A constructor does not have a return type.
It has special obligations when it comes to initializing final member variables (a method can't even assign to final members).
It's static in the sense that you can invoke it without a callee, but it's non-static in the sense that you have a this reference.
It's invoked with special keyword, new, and has a special bytecode, invokespecial, while instance methods are called by obj.method() which typically compiles to the invokevirtual bytecode.
It must invoke super constructors unless there's a no-arg constructor in super class.
They are never inherited and can not be overridden.
Directly from the JLS (Chapter 8)
A constructor is used in the creation of an object that is an instance of a class (§12.5, §15.9).
The SimpleTypeName in the ConstructorDeclarator must be the simple name of the class that contains the constructor declaration; otherwise a compile-time error occurs.
In all other respects, the constructor declaration looks just like a method declaration that has no result (§8.4.5).
Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
Constructor in Java
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
The constructor actually returns the current class instance (You cannot use return type yet it returns a value).
There are basically two rules defined for the constructor.
1)Constructor name must be same as its class name
2)Constructor must have no explicit return type
Types of constructors
1)Default constructor (no-arg constructor)
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
2)Parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
a constructor is used to initialize variables, it is not a method. you can however choose to create constructor, if you do not the JVM will create a default constructor.
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