Classes and Object Oriented Programming (OOP)


What is Object Oriented Programming

Briefly, Object Oriented Programming (OOP) is a way of organizing the code in a program. It is the process of defining classes that are used to create objects which are used to perform all of the actions of the program. For example, in the Kennel program we created classes called Kennel and Dog. Then we created PitBull, Cocker, and Chihuahua as sub-classes of Dog. When the program ran it created a Kennel object using our Kennel class as a blueprint. Next we created one object each of PitBull, Cocker, and Chihuahua and let each of these objects handle the action of "barking". In the GUI (Graphical User Interface) demonstration programs each widget (text box, button, list box, combo box, label, menubar, menu, menu item, etc.) was created as a separate object. All of these objects then worked together to implement the program. Java is a programming language that is entirely object oriented. Other programming languages, like C++, Python, etc., do not require you to use OOP, even though most programmers do.

Some important terms related to OOP

How class files are organized

A class consists of the header (public class MyApplication) in the image below, an opening brace, a list of member variables, a constructor method (function), any number of other methods (functions), and a closing brace. There must be one and only one class in a program that also contains a main() function in the format shown below. All main() should really do is instantiate one instance of the class it is in. A Java program may consist of more than one class.

Figure 4: Layout of a class file


Creating instances of classes using the new operator

In code when you want to create an instance of a class you use the new operator followed by what looks like a call to the class constructor of the class with appropriate arguments. In figure 5 below the new operator is used to create three instances of the class Dog. Each instance is passed three arguments: an int specifying the size of the Dog, a String giving the "type" of Dog, and a String giving the name of the Dog.


Figure 5: Using new to create instances of classes


The Java Library

There are many, many classes built-in to Java that you can use in your programs. All of these are listed with complete descriptions of all the member variables and methods at the Java web site. Click here to visit the library.


Figure 6: A wealth of classes can be found in the Java Library