Java Class

In this chapter you will learn:

  1. What are Java Classes
  2. Syntax of a class
  3. Example - class definition

Description

A class defines a new data type.

This new type can be used to create objects of that type.

A class is a template for an object, and an object is an instance of a class.

Syntax

The general form of a class definition is shown here:


class classname { 
  type instance-variable1; // www.j a v  a2  s .c  o m
  type instance-variable2; 
  // ... 
  type instance-variableN; 


  type methodname1(parameter-list) { 
    // body of method 
  } 
  type methodname2(parameter-list) { 
    // body of method 
  } 
  // ... 
  type methodnameN(parameter-list) { 
   // body of method 
  } 
}

A class is declared by using the class keyword.

The methods and variables defined within a class are called class members.

Variables defined within a class are called instance variables because each instance of the class contains its own copy of these variables.

The data for one object is separate and unique from the data for another.

Example

Here is a class called Box that defines three member variables: width, height, and depth.

 
class Box { /* ww w  .  ja  va2 s  .c o  m*/
    int width; 
    int height; 
    int depth; 
}

Next chapter...

What you will learn in the next chapter:

  1. Create objects from class
  2. Syntax to create objects
  3. Example - Create Java object
  4. Example - use a null mybox will result in a compile-time error