Java class Constructors initialize fields

Description

Java class Constructors initialize fields


// Using the Account constructor to the name instance
// variable at the time each Account object is created.
class Account//from  ww w.ja  v a2  s.c  om
{
   private String name; // instance variable

   // constructor initializes name with parameter name
   public Account(String name) // constructor name is class name 
   {                                                               
      this.name = name;
   }                                            

   // method to set the name
   public void setName(String name)
   {
      this.name = name; 
   } 

   // method to retrieve the name
   public String getName()
   {
      return name; 
   } 
}
public class Main
{
   public static void main(String[] args)
   { 
      // create two Account objects
      Account account1 = new Account("CSS");
      Account account2 = new Account("Java"); 

      // display initial value of name for each Account
      System.out.printf("account1 name is: %s%n", account1.getName());
      System.out.printf("account2 name is: %s%n", account2.getName());
   } 
}



PreviousNext

Related