Creating a Class with Variables
NOT TURNED IN
Create a class called
Family with the variables: lastname,
firstname, and age. The first two variables are members of the
String class and the age variable is an integer.
Now, make
the first variable "lastname" a static variable (or sometimes
called a class variable) and set it equal to string "Smith"
The following class
CreateFamily creates
a few instances of it. Add your class code to the following code
and compile it. Note that the lastname is always "Smith". Try
to change the code in
CreateFamily so that you set the
variable lastname inside of it for each instance
f1,f2.
What happens when you run the program now?
class CreateFamily {
public static void main(String arguments[]) {
Family f1, f2;
f1 = new Family();
f1.firstname = "jack";
f1.age = 99;
System.out.println(f1.firstname + " " + f1.lastname +
" is " + f1.age + " years old");
f2 = new Family();
f2.firstname = "sally";
f2.age = 39;
System.out.println(f2.firstname + " " + f2.lastname +
" is " + f2.age + " years old");
}
}
© Lynne Grewe