Create Class

In this chapter you will learn:

  1. What are Java Classes
  2. How to create a class representing a box

Introducing Classes

When you create a new class you define a new data type. Then you can define variable in the new type and use it in your code. For example, we already know String class. String class is a system class, which means it is pre-defined by Java and we can just use it. A class has it own data and provides methods which work on those data. Just like String class, the data part is the value between the double quotation marks, the operations are changing to upper or lower case, getting substring, or concatenate to another string value.

A class definition is like a template for an object, and an object is an instance of a class. A class declared by use of the class keyword has data and the code that operates on that data.

The general form of a class definition is shown here:

class classname { 
  type instance-variable1; /*j  a  v a  2 s . com*/
  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 
  } 
}

The data defined within a class are called instance variables. Each object of the class contains its own copy of the instance variables. The methods and variables defined within a class are called members of the class.

A Simple Class

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

class Box { 
    int width; 
    int height; 
    int depth; 
}

A class defines a new type of data. In this case, the new type is called Box. To create a Box object, you will use a statement like the following:

Box myBox = new Box(); // create a Box object called mybox

myBox is an instance of Box. mybox contains its own copy of each instance variable, width, height, and depth, defined by the class. To access these variables, you will use the dot (.) operator.

mybox.width = 100;

This statement assigns the width from mybox object to 100. Here is a complete program that uses the Box class:

class Box {/*from  j av  a  2  s  .  c o m*/
  int width;
  int height;
  int depth;
}
public class Main {
  public static void main(String args[]) {
    Box myBox = new Box();
    myBox.width = 10;

    System.out.println("myBox.width:"+myBox.width);
  }
}

The output:

Next chapter...

What you will learn in the next chapter:

  1. How to use class as a type and create new variables
  2. What are Object instance
  3. How to new operator to create new object instance
  4. How to assign object reference variables