Java Tutorial Java Advanced Java References

Java - Classes and Objects



Java is an object-oriented programming language. Everything in Java is associated with classes and objects, along with its attributes and methods. Java allows us to create objects. To create an object, first of all, the object should be defined in the program which is done by creating a class. A class is a code template that is used to define a new object type. Within a class, the object's attributes and methods are defined and when an object is created, its attributes and methods are determined by the class in which it is created.

Create Class

To create a class in Java, class keyword is used. It starts with the keyword followed by class name and a pair of curly braces { }. All its attributes and methods goes inside the braces:

Syntax

//defining a class
class className {
  access_specifier attribute;
  access_specifier method;
};

access_specifier: It defines the access type of the class attributes and methods. There are four types of access specifier in Java.

  • public
  • protected
  • private
  • default: When no access_specifier is mentioned

The following table shows the access to members permitted by each access specifier.

Access SpecifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
defaultYYNN
privateYNNN

Create Object

To create an object, new keyword followed by class name must be assigned to a variable (object name). To access the member of the class, dot . operator is used. See the syntax below:

Syntax

//creating an object
className objectName = new className();

//access class member (attributes and methods)
objectName.attribute
objectName.method(parameters)

Example:

In the example below, a class (new object type) called Circle is created. An object called MyCircle of the class Circle is created in the main method. The object has only one integer attribute radius which is accessed in the main method using dot . operator.

public class Circle {
  //class attribute
  int radius = 10;

  public static void main(String[] args) {
    Circle MyCircle = new Circle();

    System.out.println(MyCircle.radius);
  }
}

The output of the above code will be:

10

Class Methods

Class method must be defined inside the class definition. It is defined in the same way as a normal method is defined in Java.

Example: Class method defined inside class

In the example below, a class method called area is defined inside the class Circle. A class method is accessed in the same way as a class attribute, i.e, using dot . operator. Here, the area() class method returns the area of the circle object.

public class Circle {
  //class attribute
  int radius = 10;
  //class method
  public double area() {
    return 22/7.0*radius*radius;
  }

  public static void main(String[] args) {
    Circle MyCircle = new Circle();

    System.out.println(MyCircle.area());
  }
}

The output of the above code will be:

314.3