Constructors:

  • It is an instance method that usually has the same name as the class and can be used to set the value of members of the object.(either default or user defined values).
  • java allows themselves to create the object in which constructor helps in automatic initialize.
  • constructor not have return type and not void because the implicit return type of class constructor is a return type itself.

Example:

box(){
System.out.println("Constructing box");
width=20;
height=20;
depth=20;
}
  • since the constructor gives all boxes the same value 10 by 10 by 10 in mybox1 and mybox2 as having same dimensions & volume.

  • the default constructor automatically construct the class values as zero,null,false.It works for simple classes.but for large class we want to define the own constructor.

parameterized constructor;

  • By adding the parameter in constructor it change the dimensions of box().

This keyword: In these operation use of this is redundant but it is correct in executing like in previous version.

  • Inside box() ,THIS is referred as invoking object.

Instance variable hiding:

  • Including formal parameters overlap the local variable as same as the name of the class instance variable.

  • However when local variable has the same name as instance variable then the local variable hides the instance variable.

Syntax:

   box(double width,double height,double depth){

   this.width = width;

   this.height = height;

   this.depth = depth;
   }
  • In these formal parameter and use of local variable can hides the variable which has the same name for clarity.

Garbage collection:

  • In c++ the dynamically allocated memory is used by the delete operator.

  • But in java it is deallocates the memory automatically.This technique is called Garbage collection.

  • When no reference to object in program,then memory of particular object exist is deallocated.

Finalize() methods:

  • You can define the specific action to be destroyed or reclaimed for garbage collection.

  • It implement by finalize()method.

  • Inside the finalize() method that we want to specify those actions that must be performed before it destroyed.

     protected void finalize(){

        //...finalization code here

         }

A stack class:

  • A stacks stores the data first in and last out ordering.

  • stacks are controlled normally by push and pop.

results matching ""

    No results matching ""