Java Classes


Classes and Objects are the heart and sould of the OOP (Object Oriented Programming) and without them OOP cannot exist. In this lesson we will start our discussion on Java classes. As C++ programmers, you will glad to know that Java classesare almost the same as C++ classes. Like C++ classes, Java classescontain fields also called instance variables or properties of an object and methods. A field is like a C++ data member, and a method is like a C++ member function.

A Simple Example Class
In the following example, a List is defined to be an ordered collection of items of any type:
class List {   
  // fields       
  private Object [ ] items;    // store the items in an array
  private int  numItems;        // the current # of items in the list
                              
  //methods       

  // constructor function       
  public List() {           
  items = new Object[10];        
  numItems = 0;       
  }                          
                              
  // AddToEnd: add a given item to the end of the list     
  public void AddToEnd(Object ob){
                                
  }
}

In Java, all classes (built-in or user-defined) are (implicitly) subclasses of the classObject. Using an array of Object in the List class allows any kind of Object (an instance of any class) to be stored in the list. However, primitive types (int, char, etc) cannot be stored in the list as they are not inherited from Object.