What are the types of Constructors? Ans: In Java,there are two - TopicsExpress



          

What are the types of Constructors? Ans: In Java,there are two types of constructors. 1)Default Constructors 2)User-defined Constructors If we provide any constructor explicitly in any class then that constructor is called as User-Defined Constructor There are two types of user-defined Constructors 1.0-argument Constructor: ===================== It is a constructor with out parameters provided by the developers as per their application requirements. 2.Parametrized Constructor: ====================== It is a constructor with at least one parameter provided by the developers as per their application requirements. Ex: == class Account { String accNo; String accName; String accType; public Account(String accNo1,String accName1,String accType1) { accNo=accNo1; accName=accName1; accType=accType1; } public String toString() { System.out.println(Account is created Successfully with the following details); System.out.println(Account details); System.out.println(--------------------); System.out.println(Account Number :+accNo); System.out.println(Account Name :+accName); System.out.println(Account Type :+accType); return ; }} class Test { public static void main(String args[]) { Account acc=new Account(abc123,Durga,Savings); System.out.println(acc); }} ============================================= Output: Account is Created Successfully with the following details Account Details: ---------------------- Account Number :abc123 Account Name : Durga Account Type:Savings ============================================= In the above programme,if we set account details by using any method like setAccountDetails() then account details will be set to Account class Object after creating Object as secondary data,not as initial data,here in account object initial data will be null values [default values of String]. In the above context,if we want to set our data as initial data in the object then we have to set account details at the time of creating object,not after creating object.To achieve this,we have to use constructor to set data to Object.
Posted on: Sun, 09 Nov 2014 01:07:26 +0000

Trending Topics



/div>

Recently Viewed Topics




© 2015