Class with a constructor to initialize instance variables : Defining Class « Class Definition « Java Tutorial






public class MainClass
{
   public static void main( String args[] ) 
   {
      Account account1 = new Account( 50.00 ); // create Account object
      Account account2 = new Account( -7.53 ); // create Account object

      System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );
      
      double depositAmount; // deposit amount read from user

      depositAmount = 10.10;
      account1.credit( depositAmount ); // add to account1 balance

      System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n\n", account2.getBalance() );

      depositAmount = 12.12; 
      account2.credit( depositAmount ); // add to account2 balance

      System.out.printf( "account1 balance: $%.2f\n", account1.getBalance() );
      System.out.printf( "account2 balance: $%.2f\n", account2.getBalance() );
   }

}

class Account
{   
   private double balance; // instance variable that stores the balance

   // constructor  
   public Account( double initialBalance )
   {
      if ( initialBalance > 0.0 ) 
         balance = initialBalance; 
   }

   public void credit( double amount )
   {      
      balance = balance + amount;
   }

   public double getBalance()
   {
      return balance;
   }

}
account1 balance: $50.00
account2 balance: $0.00

account1 balance: $60.10
account2 balance: $0.00

account1 balance: $60.10
account2 balance: $12.12








5.1.Defining Class
5.1.1.What Is a Java Class?
5.1.2.Fields
5.1.3.Defining Classes: A class has fields and methods
5.1.4.Creating Objects of a Class
5.1.5.Checking whether the object referenced was of type String
5.1.6.Class declaration with one method
5.1.7.Class declaration with a method that has a parameter
5.1.8.Class that contains a String instance variable and methods to set and get its value
5.1.9.Class with a constructor to initialize instance variables
5.1.10.Specifying initial values in a class definition