General Classes
In this section, we will learn to make classes into our own specialized data types – complete with data fields and methods that operate on the data.
General class syntax
In the previous section, we looked at a specific kind of class – classes that have only static
methods. However, very few classes in Java are written with entirely static methods. In this
section, we will explore a more generic definition of a class. These generic classes in Java are
made up of three parts:
- Fields – variables that can be used throughout the class. These are also referred to as instance variables.
- Constructor – special section that initializes the fields
- Methods – perform operations on this object’s data (more on this later)
Here is the format of a general class (note that our classes with static methods also fit this syntax
– they are just a specific kind of class):
public class Name
{
//declare fields
//constructor(s)
//methods
}For now, each class should be stored in a separate file. The name of the file should match the
name of the class (including capitalization), plus the “.java” extension. For example, the class
above should be stored in the file Name.java.
Visibility modifiers
The three parts of a class (fields, constructor, methods) should be preceded by a visibility modifier. This specifies where that field, constructor, or method can be seen. There are three visibility modifiers:
public– visible anywhere the class is visibleprivate– visible only within the classprotected– discussed in the “Inheritance” section
Fields
Again, fields are special variables that can be used throughout the class. They are defined at the beginning of the class, using the following format:
visibility type name;For example:
private int size;Like typical variables, fields can also be initialized on the same line as their declaration. For example:
private int size = 0;However, initialization of fields in usually done in the constructor.
Constructor
The constructor is a special section that initializes the fields in a class. It must have the same name as the class. It can either take initial values for the fields as parameters, or it can assign them default values. Here’s the format of a constructor:
public Name(params)
{
//initialize fields
}Here, Name is the name of the class, and params are possible parameters to the constructor.
Here is a sample class with a constructor:
public class Dog
{
//fields
private String name;
public String breed;
//constructor
public Dog()
{
name = "Fido";
breed = "Mutt";
}
}When the constructor is called, the name and breed are set to the default values “Fido” and “Mutt”. We could also
accept initial values for the name and breed as parameters to the constructor:
public Dog(String n, String b)
{
name = n;
breed = b;
}We will look more at methods parameters in the next section. For now, remember that parameters must have a specified type and a name – just like in static methods.