Java examples for Object Oriented Design:Constructor
Using the Account constructor to initialize the name instance variable at the time each Account object is created.
public class Main { public static void main(String[] args) { /*from w w w . ja va 2s . c o m*/ // create two Account objects Account account1 = new Account("James Bond"); Account account2 = new Account("Michael Bates"); // 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()); } } class Account { 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; } }