Classes

(If you want to follow this tutorial, you should already be familiar with the basics of programming.)

Classes are capsuled entities containing state and behaviour. Take this class Book:

      public class Book {
        private String name;
        private int id;
        public Book(String pName,int pId) { //constructor
          name=pName;
          id=pId;
        }
        public void setName(String p) { name=p; }
      }
    

Notice the constructor which predefines the fields name and id. Also notice the access modifiers: because we hide the name and ID of a book from the outside (they are private), we have to offer the public method setName(String) if we want the name to be editable.

Let's now implement the subclass Magazine. This requires a change in the Book class:

      public class Book {
        protected String name;
        protected int id;
        //...
      }
    

The protected modifier allows subclasses to inherit a field or method from a superclass. Protected members are not accessible from the outside except by subclasses of the declaring class.

      public class Magazine extends Book {
        private String issue;
        public Magazine(String pName,int pId,String pIssue) {
          super(pName,pId);
          issue=pIssue;
        }
      }
    

The Magazine class inherits all protected and public fields from its superclass. Notice the call of the superclass constructor which defines the name and id for this subclass. Everything happens inside the Magazine class, which simply inherits all behaviour from its parent. Take an example, in which we introduce the creation of objects:

      Book a=new Book("Introduction to Digital Image Processing",1005);
      Magazine b=new Magazine("Dat Security",2050,"11/17");
      b.setName("Data Security");
    

Let's go line by line: First we create a Book object (the Book constructor sets the fields to the desired values) and bind it to the variable a. Then we create a Magazine in a similar fashion (the Magazine constructor uses the super constructor to define some fields, and the object inherits protected and public members of the superclass) and bind it to b. Finally, we notice the typo in line 2 and use the method setName(String) on the Magazine object - this method was, of course, inherited from Book.

Let's say you want to collect all Books into a list. You can use the java.util.ArrayList class for this purpose:

      ArrayList<Book> c=new ArrayList<>();
      c.add(a);   //Book: OK
      c.add(b);   //Magazine extends Book: OK
    

ArrayList is a generic class, which will operate on any given type it is declared with. So you can put elements of any type into an ArrayList<Object>, but only Books into an ArrayList<Book>. Notice the <> above: this diamond will infer the generic type from the variable declaration, in this case Book.

To write your own generic class, you supply a generic type to the class declaration:

      public class Envelope<T> {
        private T content;
        public Envelope<T>(T p) {
          content=p;
        }
      }
    

This will allow the (rather useless) Envelope class to contain any type. (T is just a conventional name for the generic type parameter, it could be any other valid identifier.) Notice that all occurences of T will be overridden by the type given at declaration; so the constructor of Envelope<Book> would accept exactly this type, and the private field content would also be of this type.

Another important concept is that of static members. Static members should be accessed from class context, and non-static members must be accessed from object context. What does this mean? Take a look:

      public class List {
        public static final int maxLength=100;
        private int[] l=new int[maxLength];
        private int li=0;
        public List() {}
        public addItem(int p) {
          l[li++]=p;
        }
      }
    

Observe the keyword static, which makes the field maxLength a property of the class itself. The final keyword makes maxLength a constant: it can not be modified during the runtime of the program. Therefore it is no problem to declare the field as public - anyone can read the field, but not modify it.
Back to the static keyword: An instance of List always has a maxLength built in, and because it is a constant, the instance can not even modify the maxLength field. On the other hand, the class List can access maxLength by itself, without needing an object inbetween. It goes like this:

      List a=new List();
      a.addItem(1); //object context
      int b=List.maxLength; //class context
    

The addItem method is executed by a List object (an instance of the List class, to make it clear). We apply something to a running instance of List. This is nothing new; but in line 3, we access the static field maxLength through the class context of List. We read a value from the blueprint of List itself.

To conclude the break-neck tour of Java classes, let's look at nested classes. You can nest a class into an outer class: if the nested class is not static, it is called inner class.

      public class Machine {
        private double maxInput;
        private Engine engine=this.new Engine();
        //fields ...
        private class Engine {
          //...
          private double computeTorque(double force) { /*...*/ }
        }
        public double getEnergyOutput(double pForce, ... /* etc. */) {
          double a=engine.computeTorque(pForce);
          //...
        }
      }
    

The inner class Engine can access all members of the Machine class, even private fields or methods. The nesting of classes can be used for increased capsulation (abstraction of an underlying process). This is exactly what is done inside the method getEnergyOutput: the object engine, created from the private inner class Engine, is assigned to compute something. The result is bound to the local variable a, and the method getEnergyOutput continues.

You might have noticed the funny declaration of the field engine - this is required because an inner class can only be instantiated by an object of its outer class. As you might know, this is a keyword describing the instance of the current class: therefore it is the correct way of creating an object of Engine.