Introduction to Software Development
GWU Computer Science
By the end of this module, you will be able to:
If you do not have your Codio course ready, use any text editor or simple IDE. Some possibilities are:
Objects:
Where does this leave classes?
Take the example of the Facebook user class:
public class FBUser {
private long userId;
private String firstName, lastName;
private FBUser[] friends;
public void setId(long id) {
userId = id;
}
public long getId() {
return userId;
}
}
The class gives the blueprint for each object:
What function do objects provide compared to variables, arrays, etc? How do they relate to static variables stored in classes?
Activity 1 (1-minutes): Create the application class FBUserTest:
public class FBUserTest {
public static void main(String[] args) {
long id = FBUser.getId();
System.out.println(id);
}
}
We're trying to invoke the getId method just like we've called static methods in the past. What do you think will happen when you compile your code? When you run it? Try!
Multiple objects exist, each with possibly different sets of data. Objects are allocated with new .
public static void main(String[] args) {
FBUser user1 = new FBUser();
FBUser user2 = new FBUser();
user1.setId(5);
System.out.println(user1.getId() + " " + user2.getId());
}
Methods in a class can operate on an object using the dot notation. If var is a variable referring to an object,
var.methodName();
invokes the methodName method on var's object.
Read this as "we're invoking the methodName method of the var object"
When an object is allocated with new, e.g.:
A var = new A();
A reference to the new object's memory is returned.
The variable (var here) is set to this reference.
This should feel familiar -- its the same as with arrays.
The type of the variable is the name of the class:
A var = new A();
The variable itself:
A var = new A();
A slightly more complicated example:
FBUser var1 = new FBUser();
FBUser var2 = var1;
var2.setId(10);
System.out.println(var1.getId());
Second, create four FBUser objeccts inFBUserTest, initiallize them all, and populate their friend lists.
Another example:
public class ObjExample {
private int data;
public void modify(int v) {
data = v;
}
public int access() {
return data;
}
public void addData(ObjExample o) {
data += o.access();
}
public static void main(String[] args) {
ObjExample v1 = new ObjExample();
ObjExample v2 = v1;
v2.modify(10);
System.out.println(v1.access());
ObjExample v3 = new ObjExample();
v3.modify(3);
v3.addData(v2);
System.out.println(v3.access());
v3.addData(v3); // what's happening here?
v1.addData(v2); // ...and here?
}
}
What are the last two lines doing? Describe them