Tuesday, August 1, 2023

java Constructors

 

                         Constructors

Constructor:

       Creating an object

Destructors:

       Deleting an object

Characteristics of Constructors

·      The Constructor name should be same as the class name.

·      it should be declared public

·      It should not have any return value/type

·      Initializes that object's instance variables, either to their initial vales or to a default(0 for numbers,null for objects,falsw for Booleans,'\0' for characters)

·      First function that gets executed as soon as an object is created, before the new operator completes.

·      It can be overloaded.

 

Types of Constructors

·      Default Constructors- Constructor without arguments

·      parameterized constructors- Constructor with arguments

·      Copy Constructors- Constrctor without arguments but the argument will be an object

 

Example

File name : Person.java

class Person{

    String name;

   int age;

   Person()

   {

     name="Unknown";

     age=0;

}

  Person(String n, int a){

    name=n;

    age=a;

}

 void show(){

       System.out.println("Name: "+name+" , Age: "+age);

}

public static void main(String args[]){

  Person p;

  p=new Person();  

  p.show();

  p=new Person("Babu",35);

  p.show();

   }

}


The output appears as given below:

 


 

This Keyword

This keyword can be used inside any method to refer to the current object.

File name: Point.java

class Point{

    int x,y;

    Point(int x,int y)

    {

             this.x=x;

             this.y=y;

    }

    void display()

    {

         System.out.println("x= "+x+"and  y= "+y);

   }

   public static void main(String args[])

   {

          Point pp = new Point(10,20);

          pp.display();

   }

}


The output appears as given below:

 


Overloading Constructors

 

File name: Cons.java

class Cons{

       double width,height,depth;

       Cons(double w,double h,double d){

              width=w;

              height=h;

              depth=d;

      }

     //constructor used when no when no dimensions specified

    Cons() {

    width=-1;          //use-1 to indicate

    height=-1;       //an uninitialized

    depth=-1;       //box

    }

    //contructor used when cube is created

   Cons(double len) {

    //this can be used to call different constructor from same class.

   this(len,len,len);

   }

   void volume()

  {

      System.out.println("volume:"+width*height*depth);

  }

}

File name: ConsOverload.java

class ConsOverload {

   public static void main(String args[]) {

      Cons mybox1=new Cons(10,20,15);

      Cons mybox2=new Cons();

      Cons mycube=new Cons(7);

     mybox1.volume();

     mybox2.volume();

     mycube.volume();

     }

}


Output:

 


Passing Objects to constructors

File name: Constructor.java

class Constructor{

double width;

double height;

double depth;

Constructor(double w,double h,double d)

{

       width=w;

       height=h;

       depth=d;

}

Constructor(Constructor ob){           //pass object to constructor

          width=ob.width;

          height=ob.height;

         depth=ob.depth;

     }

void volume()

{

System.out.println("Volume is:"+width*height*depth);

}

}

File name: ConsOverloaded.java

class ConsOverloaded {

       public static void main(String args[]) {

        Constructor mybox1=new Constructor(10.0,20.0,15.0);

        Constructor mybox2=new Constructor(mybox1);

        mybox1.volume();

        mybox2.volume();

      }

}


Output


           

Garbage Collection

Objects are dynamically allocated by using the new operator.The deallocation of unused memory is handled automatically.This is called Garbage collection.

Finalizer Methods

protected void finalize(){

....

}

More About Classes

Access Specifiers

default - Memers with default access can be accessed by other classes in the same package.

Public   - method and variable can be accessed by any other code.

Private  - method and variable can only be accessed by other members of its class.

protected - method and variable can only be accessed by its subclasses.

File name: Test.java

class Test{

             int a;//default access

             public int b;// public access

             private int c;//private access

             void setC(int a)

             {

                           c=a;

             }

             int getC()

             {

                          return c;

             }

}

File name: AccessTestDemo.java

class AccessTestDemo{

    public static void main(String args[]) {

         Test ob = new Test();

         //These are OK,a and b may accessed dir

      ob.a=10;

      ob.b=20;

      //This is not OK and will cause an compiler error

     //member method can access the private variables.

    ob.setC(100);

    System.out.println(ob.getC());

     }

}

 

Output

 


Static Variable

Example

File name: Rect.java

class Rect{

   int length;

   int breadth;

   static int count;

   Rect() {

        count++;

  }

  static {

      //static block is used to initialize static variable

     count=0;

     System.out.println("Inside static block");

  }

  public static void main(String args[])

  {

     //static variable can be accessed

    //before creating an object by its class name

    System.out.println("No of Object:"+Rect.count);

    Rect r1,r2;

   r1=new Rect();

       System.out.println("No of Object:"+r1.count);

   r2=new Rect();

        System.out.println("No of Object:"+Rect.count);

       }

}


The output appears as given below:

 


 Static Methods

Methods declared as static have several Restriction :

·      They can only call other static methods.

·      They must only access static data.

·      They cannot refer to this or super in any way.(The keyword super relates to inheritance and is described int the next chapter.)

 

Example for static methods

File name: Recta.java

class Recta{

   int length;

   int breadth;

   static int count;

   Recta() {

        count++;

    }

    static {

       count=0;

            System.out.println("Inside static block");

    }

    static void displayCount()

    {

                 System.out.println("No of Object"+count);

   }

   public static void main(String args[])

   {

       Recta r1, r2;

       Recta.displayCount();

       r1=new Recta();

       r1.displayCount();

       r2=new Recta();

      Recta.displayCount();

      }

}

 

Output :

 


0 comments:

Post a Comment