Classes comprise a second major category of types. When instantiated, the objects that result function in some ways analogous to variables albeit much more complex "variables."To function as types, classes must first be defined and then used to declare variables of their respective types. When instantiated, these variables become objects that are instances of their respective class types.
Three steps are included in this process:
Since the emphasis here is on using classes to define things, the discussion will include the simplest form of class definition; later, it will be extended to cover other facets of the construct.
- Defining a class
- Declaring a variable of type class
- Creating an instance (object) of type class
Defining a class
A class is a program block, bounded by curly braces ({ }
). It begins with the keyword,class
, followed by thename
of the class. Optionally, the keyword class may be preceded by a designation of the scope of the class, such aspublic, private
orprotected
. These concepts will be explained in more detail later, but for now we'll define all classes to bepublic
, indicating that they can be referenced from any other class.If the class is a subclass that
extends
another class, the keywordextends
follows the class name, followed in turn by the name of the superclass.Inside the class definition come variables for the class and methods that, normally, are provided to operate on those variables.
The code fragment that follows illustrates class definition.
public class LinkedList { //variables String[ ] aList; int nItems = 0; int [ ] before; int [ ] after; //methods public LinkedList ( ) { // constructor that initializes variables aList = new String [ 100 ]; before = new int [ 100 ]; after = new int [ 100 ]; } // end LinkedList constructor public boolean add ( String string ) { return true; } // end add public boolean delete ( String string ) { return true; } // end delete public boolean find ( String string ) { return false; } // end find }// end LinkedListDeclaring a variable of type class
Once the class,
LinkedList
, is defined, it can use it to declare specific linked lists or variables of that type:LinkedList list1; list1 = new LinkedList ( ); LinkedList list2 = new LinkedList ( );Creating an instance of type class
Once a variable of type class is created, it can be instantiated to create an actual object of that type.LinkedList list1; //declaration list1 = new LinkedList ( ); //instantiation LinkedList list2 = new LinkedList ( ); //declaration and instantiationOnce a specific instance is created (e.g., a particularLinkedList
), it can be asked to perform various tasks, relative to its variables, by sending a message to one of its methods. Thus:list1.add("Jim"); list2.delete("Betty"); list1.find("John");Note, that these statements first refer to the object (list1
orlist2
) and then to the method contained within its class. The two parts of the statement are joined by a period ( . ).