21-01-25 ----------- Q)Example Program on default constructor. class Account{ int accno; String name; float balance;//instance variables Account(){ accno=100001; name="Rama"; balance=770000; }//default constructor void displayAccountData(){ System.out.println("ACCNO:"+accno); System.out.println("NAME:"+name); System.out.println("BALANCE:"+balance); } }//Account data type created class DefaultConstructorApplication{ public static void main(String args[]){ Account acc1=new Account(); System.out.println("First account details.........."); acc1.displayAccountData(); Account acc2=new Account(); System.out.println("Second account details.........."); acc2.displayAccountData(); } } Q)Example program on parameterised constructor. class Account{ int accno; String name; float balance;//instance variables Account(int ano,String nm,float bal){ accno=ano; name=nm; balance=bal; }//parameterised constructor void displayAccountData(){ System.out.println("ACCNO:"+accno); System.out.println("NAME:"+name); System.out.println("BALANCE:"+balance); } }//Account data type created class ParameterisedConstructor{ public static void main(String args[]){ Account acc1=new Account(101,"Rama",40000); acc1.displayAccountData(); Account acc2=new Account(102,"Rahim",50000); acc2.displayAccountData(); } } Q)How is a constructor different from an instance method? =>A constructor is different from an instance method in the following areas. 1)Name* 2)Return type 3)Purpose 4)Type of calling 5)Time of calling 6)frequency of calling 7)who calls it 8)Is it the behaviour of the object? constructor instance method ************************************************* 1)class name generally not and constructor name should be the same. 2)should not have should have return type. return type. 3)mostly constructor mostly, data processing is meant for object code is written here. initialization 4)It is called implicitly It should be called explicitly (automatically) 5)object creation time After the object is bound to the reference 6)called only can be called any number of times. once in the lifetime of an object. 7)JVM calls it. other method can call it. 8)It is not at It is. all the behaviour of the object. ***************************************** Q)Can an object of a Java class be created without explicitly writing a constructor in that class? =>Yes. =>In a Java class if we don't write a constructor explicitly, Java compiler provides by default, a zero argument constructor for the class. Therefore, zero argument constructor has got name called "default constructor". class A{ A(){ }//explict default constructor } class B{ }//It has implicit default constructor