Class

Human, dog, car… are real-world entities. In java, classes are used to describe real-world entities.

In general, class declarations can include these components, in order:

  1. Access Modifiers such as public, private, and a number of others that you will encounter later.
  2. The class name, with the initial letter capitalized by convention.
  3. The class body, surrounded by braces, {}.

javaClass

A class can be extended from another class or implemented one or more interfaces. We will discuss later in other chapter.

Fields

Member variables in a class are called fields. The Human class uses the following lines of code to define its fields:

Field declaration is composed of three components, in order:

  • Access modifiers, such as public or private…
  • Data type, such as int or String…
  • Name

Methods & Constructors

Methods

setName(), setAddress() & introduce() are methods in the example.

Method declaration is composed of six components, in order:

  1. Modifiers—such as public, private, and others you will learn about later.
  2. The return type—the data type of the value returned by the method, or void if the method does not return a value.
  3. The method name
  4. The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
  5. An exception list – to be discussed later.
  6. The method body, enclosed between braces—the method’s code, including the declaration of local variables, goes here.

Exceptions are discussed in a later lesson.

Constructors

Constructor in java is a special method that has:

  • Name is same as class name
  • No return value

Constructors are normally used to initialize the object such as set default values.

The main Method

In the above example, an instance (object) of Human class is instantiate by calling its constructor using new key word. Then introduce() method is called to print message to standard output (console window).

The following code snippet is another example of the main method:

In the Java programming language, every application must contain a main method whose signature is:

The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose “args” or “argv”.

The main method accepts a single argument: an array of elements of type String. This array is the mechanism through which the runtime system passes information to your application. For example:

Finally, the line:

uses the System class from the core library to print message to the standard output.