calling non-static method without instance variable - java

I’m trying to figure out the below code. ImageIcone called “non-static method” getImage() according to Java API without any instance variable:
public void paintComponent(Graphics g) {
Image img = new ImageIcon("imgtest.jpg", "description...").getImage();
g.drawImage(img,3,4,this);
}

This
new ImageIcon("imgtest.jpg", "description...")
creates an instance. The getImage() method is invoked on that instance and then all references to that instance are lost. The object can then be garbage collected if it is unreachable.
Remember, all you need to invoke an instance method is an expression that resolves to an object reference. A variable of a reference type is one such expression. A constructor invocation is another such expression. An invocation of a method with a return type of some reference type is also such an expression.

You don't need an 'instance variable.' You only need an instance, and new ImageIcon("imgtest.jpg", "description...") is the instance.

In your code,you are creating an anonymous object of ImageIcon class by using the code new ImageIcon("imgtest.jpg", "description..."). Since you are not going to use that object in future,that's why you are opting to create an anonymous object.

Related

Constructors does not have any return types but then how object is created?

According to the definitions of constructors they don't have any return types,but while creating object we often do A a = new A(); which is responsible for creating the object a.
A a=new A();
Can anyone help me understanding the issue,what is actually happening in the case of constructors while creation of Object.
Constructors don't have return types, correct. But the expression new A() does have a result: A reference to the newly-created object.
Here's what happens with new A():
An object is created
It's given the type A
The relevant A constructor is called with this referring to that new object
Once initialization is done, the expression completes
The result of the expression is the reference to the new object
This process is described in this tutorial on the Oracle Java site.
In many ways, it would be more accurate to call constructors initializers: The construction happens because of the new operator, not the constructor.
The fact that constructors don't actually do the construction is made particularly clear when an object is processed by multiple constructors, as is very common. Consider:
List<String> m = new LinkedList<String>();
One object is created (ignoring any fields the list may need to initialize), but five different constructors get called to initialize that one object, because LinkedList<E> subclasses java.util.AbstractSequentialList<E> which subclasses java.util.AbstractList<E> which subclasses java.util.AbstractCollection<E> which subclasses java.lang.Object, and each of those classes has to get its chance to initialize its part of the object that was created. So in order:
JVM creates the object
Object() is called to initialize Object stuff
AbstractCollection() is called to initialize its stuff
Then AbstractList()
Then AbstractSequentialList()
Then LinkedList()
And then finally the resulting (one) object's reference becomes the result of the new expression
One object, but five constructors required to initialize it. :-)
Constructors need not to return anything. They just constructs the current instance. That's all their job, part of object creation.
Creating objects:
A a = new A();
Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.
Constructor declarations look like method declarations—except
that they use the name of the class and have no return type - from
the java constructor docs
To understand the constructor, it is similarly important to understand how it differs from a method.
Constructors have one purpose in life: to initialize the new object and it's fields. Nothing more. The new keyword handles the creation of memory space.
You shouldn't consider new A() to be a call to the constructor, because there are more things that happen, than just the constructor running. The major steps, when you run new A() are these.
A chunk of memory is set aside - just enough for storing an object of class A.
The constructor is run.
A reference to the chunk of memory that was set aside is returned.
So the constructor itself isn't actually returning anything - and it's an error to have return this; or anything similar inside the constructor.
Return statement inside a constructor doesn't logically makes sense because the purpose of the constructor is to perform initialization. The object has not been created yet, the actual construction of the object happens in JVM.

Difference between call to a method in Java?

I just want to make clear that to call a function in two forms like
By creating an object and calling the method by using that object.
Without creating a object calling the function.
I mean for instance i have a class like
Class A{
public int callMethod(){
return 2;
}
}
Now I am creating another class to call the method callMethod defined in the Class A
Class B {
public static void main(String[] args) throws ParseException {
A a = new A();
//1st form to call the method
int aa = a.callMethod()
System.out.println(aa);
//2nd form to call the method
aa = new A().callMethod();
System.out.println(aa);
}
}
here in the first statement after creation of a object i am calling the callMethod() of class A by using the class object of A. And in the second time i am calling the method directly without creating the object class A. In the first form calling the method it is damn sure that we are creating the object and occupies some space in the memory for the object. Then what about the second form calling the method? Will it take any object creation? Which one is quicker? can anyone give me the clarifications on this.
When you use new keyword and constructor, in this case, new A(), it is creating a new object.
And in the second time i am calling the method directly without
creating the object class A.
That's not true - the object is still created, it only has no name you can refer to afterwards.
Both of your ways are creating an instance of the object but in second case you don't have variable to point to the object if you want to access the second object later you can not do it
In the second code you are creating an instance of A and it is occupying space on the stack.
The first code will require that you instantiate A on the heap space (Unless you instantiate it from static code, for example:
static {
A a = new A();
}
)
You are creating objects in the BOTH the methods. The statement
new A()
creates a new object and then you are calling a function.
You should also know that objects DO NOT get different memory space for methods. All the objects of a class share the same memory space for methods. so it really doesnt matter about the space.
If you want to call a function without using a object, you should make the function static, that way you cam call the function without actually using an object.
hope this helps.
Read about stack space and heap space in java
In java we have references referring to objects on heap space,
In both cases, it is creating object on heap space but in first case
you have reference stored on stack space with A a ("a" is reference)
So in same method or any other methos to which this reference is
passed can refer to the original object (first object created) from
heap space...
In second case you are calling methos directly on new obj which has no
reference stored on stack space to refer it afterwards like in first
case.
Both are same..!!
When you write
new A();
here Compiler calls the Non-parameterized constructor (if it is not written by programmer compiler calls the default constructor )
like:
A()
{
//i am default constructor
super();
}
note: here super(); call the immediate super-class default constructor which is the Object class and object is created.
A a = new A();
here object is created and you assign that object to reference 'a';

Why we initiate object inside 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.

Constructor is static or non static

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

When does the Constructor gets called in java?

When does the Constructor get called?
Before object creation.
During object creation.
After object creation.
The object memory is allocated, the field variables with initial values are initialized, and then the constructor is called, but its code is executed after the constructor code of the object super class.
At the byte code level.
An object is created but not initialised.
The constructor is called, passing the object as this
The object is fully constructed/created when the constructor returns.
Note: The constructor at the byte code level includes the initial values for variables and the code in the Java constructor.
e.g.
int a = -1;
int b;
Constructor() {
super();
b = 2;
}
is the same as
int a;
int b;
Constructor() {
super();
a = -1;
b = 2;
}
Also note: the super() is always called before any part of the class is initialised.
On some JVMs you can create an object without initialising it with Unsafe.allocateInstance(). If you create the object this way, you can't call a constructor (without using JNI) but you can use reflections to initialise each field.
It gets called at object creation. The memory must be reserved first for the object, otherwise the constructor code could not run. So maybe we could say after object creation. Also note that initialization code written in the class gets called before the constructor code.
public Ex {
int xVal = -1;
int yVal;
public Ex() {
// xVal is already -1.
//yVal defaults to 0.
}
}
THE JVM will first allocate the memory for your object, then initialize all fields, then invoke your constructor.
The constructor gets called when a new object is created.
NewObject n = new NewObject();
public class NewObject {
public NewObject() {
// do stuff when object created
}
}
Hope this helps.
basically constructors are called to initialize the values of the instance variables except the case for default constructors. However, this initialization of the instance variables are done in 4 steps (as applicable):
variables are initialized with default values (ints with 0, chars with u\0000 etc.)
variables are initialized with explicit initialization values
initialized with static blocks
constructors are called
After the Object creation
once an object is created using new operator like Student s = new Student();
first Student object is created, and then constructor is called to initialize the variable of the object
We can prove constructor is called after creating the object by using below code
here we are using instance block. And also instance block is executed before the constructor
so I am printing hash code in three places
Inside Instance block
Inside Constructor
Inside main mehtod
all these three times hash code is equal, that means object is created before the constructor is executed
because having a hash code means, there must be an object. And if hash code printed inside both instance block and constructor is equal. that means object must be created before the constructor execution
Constructor is what practically creates object. It is called when object is created by executing new MyClass() (or its parametrized version).
Given those options, 1. Before object creation.
After the constructor finishes, the object has been created.
Whenever we create an object by using 'new' operator then 1st task is performed by the new i.e. it allocates the memory for object in heap with pointing to the reference variable in stack and set the initial values of object fields.then it calls the constructor with passing 'this' as object to initialize it according to your requirement...
So the constructor is always called after the object creation....
Note: When you enter in constructor so 'this' keyword is working means your object has been created.

Categories