Java Classes - How to Declare a Class (Page 2 of 5 )
There are several ways to define your classes. The simplest would be:
class YourClass {
declare your field, constructor, and methods here
}
You can also define them in a more complex manner:
class YourClass extends YourSuperClass implements SomeInterface {
declare your field, constructor, and methods here
}
Here is a list of components class declarations can contain:
Public, Private, and other modifiers.
Class Name.
Superclass name, if applicable with the keyword extends before it.
The keyword implements followed by a list of interfaces (separated by commas).
Body of the class, encapsulated with braces{}.
Variables in Classes
We discussed variables and data types in a previous article, but they need a little further discussion here, as they relate to classes.
Variables in classes are known as member variables and are called fields. They are composed of a modifier (such as public or private), a type, and a name. An example would be:
public int myEnormousIQ;
In the above example, the public portion of our declaration is known as an access modifier. It determines which classes have access to the member field. There are several access modifiers: public, protected, package, and private.
Public: can be referenced from anywhere in the application by the class in which it is defined.
Package: can be referenced by only the same package through the class in which it was defined.
Private: can only be referenced by the class in which it was defined.
Protected: can be referenced by its class and subclass and from its package.
Next: Using Public Methods to Obtain Private Fields >>
More Java Articles
More By James Payne