"new " and "this" keywords
The "new" keyword
- The new keyword does the following tasks for us,
- Dynamically allocates memory for the object on heap space.
- Creates object reference on the heap stack.
- Returns a reference to this object.
- Reference is stored in a variable.
The objects can be declared using object reference, such as
Employee employee; Student student;
Employee employee=new Employee(); Student student=new Student();
The "this" keyword
- Each class member function has an implicit reference to its own class object, named “this”.
- this implicit reference is created automatically by the compiler itself.
- It returns the reference of the object from which it is invoked.
- "this" keyword enables us to resolve the name collision between member variable and method arguments.
- this can also be used to refer to overloaded(see Polymorphism in Java) class constructors.
- It can’t be used with static methods.
For example
public class Circle { float radius; static float pi=3.14f; public Circle() { } public Circle(float radius) { this(); //referring constructor this.radius=radius*(pi); } }
Using new and this together
class Box{ int h,w,l; public Box(int h, int w, int l) { super(); this.h = h; this.w = w; this.l = l; } public void displayVolume() { System.out.println("Volume "+ h*w*l); } } public class ArrayTest { public static void main(String[] args) { Box box[]=new Box[5];// create an Array of Boxes box[0]=new Box(10,21,13);//create five Boxes box[1]=new Box(11,19,44);//Add to Array box[] box[2]=new Box(21,17,26); box[3]=new Box(14,11,28); box[4]=new Box(17,22,19); for(Box b:box) { b.displayVolume(); } } }