Page 267 - PowerPoint Presentation
P. 267
CAVITE STATE UNIVERSITY
TRECE MARTIRES CITY CAMPUS
Department of Information Technology DCIT 111 - Advanced Programming
public class TestStudent { // main class
public static void main(String[]args) {
Student Student1 = new Student();
Student1.id = 101; // here you are initializing an object
Student1.name = “Christian”; // in other words, you’re storing data into the object.
System.out.println(Student1.id + “ “ + Student1.name);
}
}
We can also create multiple objects and store information in it through reference variable.
class Student { // THIS IS A CLASS
int id;
String name;
}
public class TestStudent {
public static void main(String[]args) {
Student Student1 = new Student(); // Creating the Object
Student Student2 = new Student();
Student1.id = 101;
Student1.name = “Christian”; // Initializing and storing value on the object1
Student2.id = 102;
Student2.name = “Miguel”; // Initializing and storing value on the object2
System.out.println(Student1.id + “ “ + Student1.name); // Printing the values of objects
System.out.println(Student2.id + “ “ + Student2.name);
}
}
Object and Class Example: Initialization through method
In this example, we are creating the wo objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the state
(data) of the objects by invoking the displayInformation() method.
class Student { // This is the class
int ID;
String Name;
// NOTE : methods should be inside the class
void insertRecord(int id, String name) { // parameterized method is used to provide different
values to distinct objects.
ID = id; // declaring variable and parameters must be familiar to each other
Name = name; // example: name = Name
} // This is a method insertRecord()
void displayInformation() { // THIS IS ALSO A METHOD displayInformation()
System.out.println(ID + “ “ Name);
} }
43