62 Program on How to Initialize the non-static / Instance Variable by using Constructor in Java

Code:

//How to Initialize the non-static / Instance Variable by using Constructor

import java.util.Scanner;
class Account
{
long accNo;
String accHoldName;
static Scanner scan = new Scanner( System.in );

Account( long no , String name )
{
accNo = no;
accHoldName = name;
}

public static void main( String args[] )
{
System.out.println(" Enter number customers: ");
short records = scan.nextShort();

Account acc[]  = new Account[ records ];

for( int i = 0 ; i < acc.length ; i++ )
{
System.out.print("\n\n Enter customer "+(i+1) +" Account Number: ");
long no = scan.nextLong();

System.out.print(" Enter Holder Name: ");
String name = scan.next();
Account obj = new Account(no , name);
acc[i] = obj;
}

for( int i= 0 ; i < acc.length ; i++ )
{
Account obj = acc[i];
System.out.println("\n\n Customer "+(i+11)+" details:");
System.out.println(" Account Number: "+obj.accNo);
System.out.println(" Account Holder Name: "+obj.accHoldName);
}

}
}

Output:



Previous
Next Post »