Lecture 2
Lecture 2
Programming
with Java II
Email: m_khamis@ci.suez.edu.eg
Lecture outcomes
• What are accessor and mutator methods.
• Scoping rules
initializations
• e.g., one version sets all attributes to default values while another version sets some
• You should always do this for variable attributes, very rarely do this for
methods.
*/
}
Q: Life of an object?
Dr. Mohamed K. Hussein 16
When to Use: Locals
• Local variables: temporary information that will only be used inside a method
public nameFamily()
{
int i;
Scanner in = new Scanner(System.in);
for (i = 0; i < 10; i++) Scope Scope of
{
of ‘i’ ‘in’
(int) (Scanner)
childrenName[i] = in.nextLine();
}
}
• Q: Does it make sense for every ‘Person’ to have an ‘i’ and ‘in’ attribute?
Dr. Mohamed K. Hussein 17
Scoping Rules
• Rules of access
1. Look for a local (variable or constant)
2. Look for an attribute
Second: look for the
definition of an attribute
public class Person e.g., “private int x;”
{
First: look for the
public void method() definition of a local
{ identifier e.g., “int x;”
x = 12;
}
} Reference to
an identifier
???
• Method signature
• Encapsulation/information hiding
Dr. Mohamed K. Hussein 23
Assignment 2
• Methods to allow the user to enter this data and display it.
• Two member functions: getDate(), which allows the user to enter a date
in 12/31/02 format, and showDate(), which displays the date.