Introduction:
Hello and welcome to a tutorial on Object Oriented Programming, with code examples as opposed to theory.
Ready the theory page
Before starting this page make sure you have read and understand the theory page which can be found
here.
Instances
The use of OOP is to have multiple instances of one class running at the same time, each with it's own variables and methods. For the tutorials below I am going to use an example of a worker/student database where user information gets entered to a database.
Examples:
So, first we need to create a class where we want to run the instances of our OOP from as well as the OOP class which will contain the variables and methods of our OOP variable types...
Main class:
public class Main {
public static void main
(String args
[]) {
//This is ran first out of everything. It's also commented out by the front two "//" so this line doesn't get ran.
}
}
OOP class:
public class Student {
private int age;
public Student
(String fName,
String lName,
int studentAge
) {
this.firstName = fName;
this.lastName = lName;
this.age = studentAge;
}
}
So now we are going to create a few user variables using our "Student" OOP class. In our constructor for our "Student" class we accept the arguments; First Name, Last Name and Age, so we must write these when creating our new variables...
public class Main {
public static void main
(String args
[]) {
//This is ran first out of everything. It's also commented out by the front two "//" so this line doesn't get ran.
Student first = new Student("John", "Qwop", 34);
Student second = new Student("Sam", "Sail", 16);
Student third = new Student("Lisa", "Porter", 23);
}
}
Now we have created some variables through OOP. We can now use the methods created in our OOP ("Student") class while keeping them separate. To show this, here is a custom method in the "Student" class which output the information to the console of the student:
public void outputDetails() {
System.
out.
println("This student is " + this.
firstName + " " + this.
lastName + " and is " + this.
age + " years of age.");
}
Here is the use of that method from our Main class on all created students...
first.outputDetails();
third.outputDetails();
And here is the output in the console once the program has finished running...
This student is John Qwop and is 34 years of age.
This student is Lisa Porter and is 23 years of age.
Finished!