Instance variables, Local variables and Method Parameters


Instance variables:
-are mainly use to store objects's state 
-visibility can be controlled by using appropriate scope (public, private, protected,default)
-lifetime is limited to containing object's lifetime

Local variables and Method parameters:
-are local to specific method 
-visibility can not be controlled its only visible inside the defined method
-lifetime is temporary and only limited to method scope
======================================================
Example: To demonstrate different types of variables
public class Customer {   
     private String lastName; //instance variable
     private String firstName; //instance variable
    
     public String getLastName() {
          return lastName;
     }
     public void setLastName(String lName) { //parameter 
          lastName = lName;
     }
     public String getFirstName() {
          return firstName;
     }
     public void setFirstName(String fName) {
          firstName = fName;
     }
     //Returns full name by concatenating Last and First name
     public String getFullName() {
          String fullName; //local variable
          fullName = getLastName() + " " + getFirstName();
          return fullName;
     }
}

No comments :

Post a Comment