J.E.D.I
10.3 Declaring Attributes
To declare a certain attribute for our class, we write, modifier type name [= default_value];
Now, let us write down the list of attributes that a student record can contain. For each information, also list what data types would be appropriate to use. For example, you
dont want to have a data type int for a students name, or a String for a students grade.
The following are some sample information we want to add to the student record. name
- String address
- String age
- int math grade
- double english grade
- double science grade
- double average grade
- double You can add more information if you want to, its all really up to you. But for this
example, we will be using these information.
10.3.1 Instance Variables
Now that we have a list of all the attributes we want to add to our class, let us now add them to our code. Since we want these attributes to be unique for each object or for
each student, we should declare them as instance variables.
For example,
public class StudentRecord {
private String
name;
private String
address;
private int
age;
private double
mathGrade;
private double
englishGrade;
private double
scienceGrade;
private double average;
well add more code here later }
where, private here means that the variables are only accessible within the class. Other objects
cannot access these variables directly. We will cover more about accessibility later.
Coding Guidelines:
1. Declare all your instance variables on the top of the class declaration. 2. Declare one variable for each line.
3. Instance variables, like any other variables should start with a SMALL letter. 4. Use an appropriate data type for each variable you declare.
5. Declare instance variables as private so that only class methods can access them
directly.
Introduction to Programming I 151
J.E.D.I
10.3.2 Class Variables or Static Variables
Aside from instance variables, we can also declare class variables or variables that belong to the class as a whole. The value of these variables are the same for all the
objects of the same class. Now suppose, we want to know the total number of student records we have for the whole class, we can declare one static variable that will hold this
value. Let us call this as studentCount.
To declare a static variable,
public class StudentRecord {
instance variables we have declared
private static int studentCount;
well add more code here later }
we use the keyword static to indicate that a variable is a static variable. So far, our whole code now looks like this.
public class StudentRecord {
private String name;
private String address;
private int age;
private double mathGrade;
private double englishGrade;
private double scienceGrade;
private double average;
private static int studentCount; well add more code here later
}
10.4 Declaring Methods