Object Oriented Programming(OOP) Explained with Java Examples (Part 2)

In the first part of the Object Oriented Programming lessons, you learnt:

  • How to create classes
  • How to create a subclass and inherit from a superclass
  • How to extend a  class
  • How to define class methods
  • How to inherit methods from a superclass
  • Concept of Inheritance (the subclass inherits the properties of the superclass)

In this lesson, we would use these classes and actually use these classes in our main program to see how it works.

Step 1: Open the OOPLesson project

Step 2: In the main program, type the following lines immediately after the line that begins with package

import MyClasses.Person;
import MyClasses.Patient;
import MyClasses.Physician;

This lines tell the compiler that we would like to use these classes in the main program. If you have done this correctly, your program should look like this:


Step 4: Write the following lines of code inside the main function:
Person myPerson = new Person(10);  //CREATES A PERSON OBJECT myPerson WITH A PARAMETER SSN
myPerson.setFirstname(“Oleander”);  //ASSIGNS Firstname TO myPerson
myPerson.setLastname(“Yuba”);       //ASSIGNS Lastname TO myPerson
myPerson.setEmail(“oleandery@gmail.com”); //ASSIGNS Email TO myPerson  System.out.println(myPerson.getFirstname());  //PRINTS THE FIRSTNAME
System.out.println(myPerson.getLastname());   //PRINTS THE LASTNAME
System.out.println(myPerson.getEmail());      //PRINTS THE EMAIL
If you have done this correctly, then your code would look like the one below.

Step 5: Run the program and observe the output

Step 6: Follow the same procedure to create myPatient object

Step 7: Follow the same procedure to create myPhysician object

Step 8: Take some time to understand how  the program works

Final Notes
In this lesson, Object Oriented Programming(OOP) Explained with Java Examples (Part 2), you have been able to create objects based on the classes you created. This is called instantiating the class, that is creating objects from the class.
You have also learnt how to assign attributes to the object you created using the public methods of the classes

In the next lesson 3, we would learn about Static Methods and Abstract Classes.

This is lesson 1, in case you want to do a review:
Object Oriented Programming(OOP) Explained With Java Examples (Part 1)