2. Classes

A class is a blueprint or prototype that you can use to create many objects.

classDeclaration { 
  memberVariableDeclarations
  methodDeclarations 
}

At minimum, a class declaration must contain the class keyword and the name of the class that you are defining:

class NameOfClass {
    . . .
}

2.1.1. Declaring a Class's Superclass

In Java, every class has a superclass. If you do not specify a superclass for your class, it is assumed to be the Object class (declared in java.lang).

class NameOfClass extends SuperClassName {
    . . .
}

A subclass inherits variables and methods from its superclass.

2.1.2. Listing the Interfaces Implemented by a Class

An interface declares a set of methods and constants without specifying the implementation for any of the methods. When a class claims to implement an interface, it's claiming to provide implementations for all of the methods declared in the interface.

class ImaginaryNumber extends Number implements Arithmetic {
    . . .
}

2.1.3. Summary of a Class Declaration

[ modifiers ] class ClassName [ extends SuperClassName ] [ implements InterfaceNames ] {
    . . .
}
  • modifiers declare whether the class is public, abstract, or final

  • ClassName sets the name of the class you are declaring

  • SuperClassName is the name of ClassName's superclass

  • InterfaceNames is a comma-delimited list of the interfaces implemented

Audio in Portuguese

class IntegerClass {
  int anInteger;
  . . . // define methods here . . .
}
[Caution]Caution

A member variable and a method can have the same name.

In short, a member variable declaration looks like this:

[accessSpecifier] [static] [final] type variableName
  • accessSpecifier defines which other classes have access to the variable. You control access to methods using the same specifiers, so Controlling Access to Members of a Class covers how you can control access to both member variables and methods.

  • static indicates that the variable is a class member variable as opposed to an instance member variable. You also use static to declare class methods. Instance and Class Members talks about declaring instance and class variables and writing instance and class methods.

2.2.1. Declaring Constants

class Avo {
  final double AVOGADRO = 6.023e23;
}
returnType methodName() {
      . . . 
}
[Caution]Caution

In Java methods arguments are passed only by value.

2.3.1.1. The Method Body
. . .
boolean isEmpty() {
    if (topelement == STACK_EMPTY)
            return true;
    else
            return false;
}

Audio in Portuguese

Table 4.1. Access to Members of a Class

Specifierclasssubclasspackageworld
privateX   
protectedXXX 
publicXXXX
packageX X 

2.4.1. Private

The most restrictive access level is private. A private member is accessible only to the class in which it is defined.

class Alpha {
    private int iamprivate;
    private void privateMethod() {
        System.out.println("privateMethod");
    }
}
class Beta {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iamprivate = 10;      // illegal
        a.privateMethod();      // illegal
    }
}

2.4.2. Protected

It allows the class itself, subclasses, and all classes in the same package to access the members.

package Greek;
public class Alpha {
    protected int iamprotected;
    protected void protectedMethod() {
        System.out.println("protectedMethod");
    }
}
package Greek;
class Gamma {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iamprotected = 10;    // legal
        a.protectedMethod();    // legal
    }
}
package Latin;
class Delta extends Alpha {
    void accessMethod(Alpha a, Delta d) {
        a.iamprotected = 10; a.protectedMethod();   // illegal
        d.iamprotected = 10; d.protectedMethod();   // legal
    }
}

Audio in Portuguese

2.4.3. Public

Any class, in any package, has access to a class's public members.

package Greek;

public class Alpha {
    public int iampublic;
    public void publicMethod() {
        System.out.println("publicMethod");
    }
}
import Greek.*;

package Roman;

class Beta {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iampublic = 10;       // legal
        a.publicMethod();       // legal
    }
}

The last access level is what you get if you don't explicitly set a member's access to one of the other levels. This access level allows classes in the same package as your class to access the members.

package Greek;

class Alpha {
    int iampackage;
    void packageMetho() {
        System.out.println("packageMethod");
    }
}
package Greek;

class Beta {
    void accessMethod() {
        Alpha a = new Alpha();
        a.iampackage = 10;     // legal
        a.packageMethod();     // legal
    }
}

Audio in Portuguese

Constructors create objects from the class blueprint.

They look like normal methods—except:

  • They use the name of the class and

  • have no return type.

For example, Bicycle has one constructor:

public class Bicycle {

    // the Bicycle class has three fields
    public int cadence;
    public int gear;
    public int speed;

    // the Bicycle class has one constructor
    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
...
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory for the object and initializes its fields.

Bicycle could have others, including a no-argument constructor:

public Bicycle() {
       gear = 1;
       cadence = 10;
       speed = 0;
}