Java class add getter and setter method

Description

Java class add getter and setter method


import java.util.Scanner;
class Account/*from  w w  w .  ja v  a2  s .c om*/
{
   private String name; // instance variable
 
   // method to set the name in the object              
   public void setName(String name)      
   {                                             
      this.name = name; // store the name
   }         

   // method to retrieve the name from the object
   public String getName()        
   {                                    
      return name; // return value of name to caller        
   }         
} 
public class Main
{
   public static void main(String[] args)
   { 
      // create an Account object and assign it to myAccount
      Account myAccount = new Account(); 

      // display initial value of name (null)
      System.out.printf("Initial name is: %s%n%n", myAccount.getName());

      myAccount.setName("new name"); // put theName in myAccount
      System.out.println(); // outputs a blank line

      // display the name stored in object myAccount
      System.out.printf("Name in object myAccount is:%n%s%n",
         myAccount.getName());
   } 
} 



PreviousNext

Related