+ 6
What is the use of new and this keyword in Java?
4 ответов
+ 5
New created an instance of an object and this is a reference to the current object.
+ 4
New keyword is used to allocate memory n create new object of a class. And this keyword is used to refer member functions n data members of the same class.
+ 1
In Java 'new' is just a holdover from C++. It doesn't really do anything, but you have to write it, when you call a constructor. It's just syntax.
this on the other hand refers to the currently active object. Example:
class Monster{
void kill (Creature creature) {...} ;
void suicide() { kill(this)} ;
}
So who gets killed on suicide? The acting monster itself.
0
'new' is used to create an instance or say an object of a class.
for example, suppose i have defined a class named 'A' now,
A ob1; - only creates a pointer or reference to the class with ni memory allocations whatsoever.
but,
A ob1;
ob1 = new A(); - not only creates ob1 as a reference but also allocates memory to it. So 'new' keyword is basically used to allocate memory.