What is Class in Java with Programming Examples

In this article, we will learn how to declare, create a Class in Java with examples. We will also look into different components classes like member variables, constructors, methods etc. A Class can be defined as a template/blueprint for creating objects which define its state and behavior.
Check out What Is Object in Java with Programming Examples

What is Class?

A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. In short, a class is the specification or template of an object.
Let’s look at an example of a class and analyze its various parts in a below diagram. This example declares the class Circle, which has the member-variables x, y, and radius of type Integer and the two member-methods, area() and fillColor().

A class is a template for creating objects

Below diagram shows a Circle class which is a template to create three objects:

A class is a construct that defines objects of the same type

The below diagram shows a Circle class with it's data fields, constructors and methods.

Examples: Creating Student Class

Let's demonstrate how to create Class in Java with an example. Here is a Student class:
package net.javaguides.corejava.oops;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";

    public Student() {
        super();
    }

    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
}

Declaring Classes

You've seen classes defined in the following way:
class MyClass {
    // field, constructor, and 
    // method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.
A Class can extend another class or implement an interface like:
class MyClass extends MySuperClass implements YourInterface {
    // field, constructor, and
    // method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
In general, class declarations can include these components, in order:
  1. Modifiers such as public, private, protected, default.
  2. The class name, with the initial letter capitalized by convention.
  3. The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
  5. The class body, surrounded by braces, {}.

Declaring Member Variables

There are several kinds of variables:
  • Member variables in a class—these are called fields.
  • Variables in a method or block of code—these are called local variables.
  • Variables in method declarations—these are called parameters.
The Bicycle class uses the following lines of code to define its fields:
public class Bicycle {
        
    private int cadence;
    private int gear;
    private int speed;
}
Field declarations are composed of three components, in order:
  • Zero or more modifiers, such as public or private.
  • The field's type.
  • The field's name.

Access Modifiers

Java supports four types of access modifiers:
  1. Private
  2. Default (no access modifier specified)
  3. Protected
  4. public

1. Private Access Modifier

A private class member cannot be accessed from outside the class; only members of the same class can access these private members.

2. Default Access Modifier (no access modifier specified)

When we do not mention any access modifier, it is called default access modifier. The scope of this modifier is limited to the package only. This means that if we have a class with the default access modifier in a package, only those classes that are in this package can access this class. No other class outside this package can access this class. Similarly, if we have a default method or data member in a class, it would not be visible in the class of another package.

3. Protected Access Modifier

If a class or its members are declared as protected are only accessible by the classes of the same package and the subclasses present in any package. You can also say that the protected access modifier is similar to default access modifier with one exception that it has visibility in subclasses.

4. Public Access Modifier

If a class or its members are declared as public, they can be accessed from any other class regardless of the package boundary. It is comparable to a public place in the real world, such as a company cafeteria that all employees can use irrespective of their department.

Defining Methods

Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines,
                              double length, double grossTons) {
    //do the calculation here
}
The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (), and a body between braces, {}.
More generally, method declarations have six components, in order:
  • Modifiers—such as public, private, protected, default.
  • The return type—the data type of the value returned by the method, or void if the method does not return a value.
  • The method name—the rules for field names apply to method names as well, but the convention is a little different.
  • 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.
  • An exception list—to be discussed later.
  • The method body, enclosed between braces—the method's code, including the declaration of local variables, goes here.

Constructors

In Java, a constructor is a block of codes similar to the method. It is called when an instance of the object is created, and memory is allocated for the object.
Every class has a constructor. If you do not explicitly write a constructor for a class, the Java compiler provides a default constructor (without any parameter) for that class.

Rules for creating Java constructor

There are two rules defined for the constructor.
  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

Constructors Example

package net.javaguides.corejava.oops;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Student {
    private String name = "Ramesh";
    private String college = "ABC";
    
    // default constructor
    public Student() {
        super();
    }

    // parameterized constructor
    public Student(String name, String college) {
        super();
        this.name = name;
        this.college = college;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCollege() {
        return college;
    }

    public void setCollege(String college) {
        this.college = college;
    }
}

More Class Examples in Java

public class Circle {
    private int xPos;
    private int yPos;
    private int radius;

    // three overloaded constructors for Circle
    public Circle(int x, int y, int r) {
        xPos = x;
        yPos = y;
        radius = r;
    }

    public Circle(int x, int y) {
        xPos = x;
        yPos = y;
        radius = 10; // default radius
    }

    public Circle() {
        xPos = 20; // assume some default values for xPos and yPos
        yPos = 20;
        radius = 10; // default radius
    }

    public String toString() {
        return "center = (" + xPos + "," + yPos + ") and radius = " + radius;
    }

    public static void main(String[] s) {
        System.out.println(new Circle());
        System.out.println(new Circle(50, 100));
        System.out.println(new Circle(25, 50, 5));
    }
}
Output:
center = (20,20) and radius = 10
center = (50,100) and radius = 10
center = (25,50) and radius = 5

Object vs Class

Summary

  • A class is a template for objects. It defines the properties of objects and provides constructors for creating objects and methods for manipulating them.
  • A class is also a data type. You can use it to declare object reference variables. An object reference variable that appears to hold an object actually contains a reference to that object.
  • An object is an instance of a class. You use the new operator to create an object, and the dot operator (.) to access members of that object through its reference variable.
  • An instance variable or method belongs to an instance of a class. Its use is associated with individual instances. A static variable is a variable shared by all instances of the same class. A static method is a method that can be invoked without using instances.
  • Visibility modifiers specify how the class, method, and data are accessed. A public class, method, or data is accessible to all clients. A private method or data is accessible only inside the class.
  • You can provide a getter (accessor) method or a setter (mutator) method to enable clients to see or modify the data. 

Related OOPS Articles

Learn complete Java at Java Tutorial | Learn Java Programming with Examples

Comments