Classes in Java

A class is a user-defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: 

  1. Modifiers: A class can be public or has default access (Refer to this for details).
  2. Class name: The name should begin with an initial letter (capitalized by convention).
  3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
  4. Interfaces(if any): 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. Body: The class body surrounded by braces, { }.

Constructors are used for initializing new objects. Fields are variables that provide the state of the class and its objects, and methods are used to implement the behavior of the class and its objects.

Example: 

Java




// Java program to demonstrate Class
 
// Class Declaration
public class Dog {
 
    // Instance Variables
    String name;
    String breed;
    int age;
    String color;
 
    // Constructor Declaration of Class
    public Dog(String name, String breed, int age,
               String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
 
    // method 1
    public String getName() { return name; }
 
    // method 2
    public String getBreed() { return breed; }
 
    // method 3
    public int getAge() { return age; }
 
    // method 4
    public String getColor() { return color; }
 
    @Override public String toString()
    {
        return ("Hi my name is " + this.getName()
                + ".\nMy breed, age and color are "
                + this.getBreed() + ", " + this.getAge()
                + ", " + this.getColor());
    }
 
    public static void main(String[] args)
    {
        Dog tuffy
            = new Dog("tuffy", "papillon", 5, "white");
        System.out.println(tuffy.toString());
    }
}


Output

Hi my name is tuffy.
My breed, age and color are papillon, 5, white

Differences between Interface and Class in Java

This article highlights the differences between a class and an interface in Java. They seem syntactically similar, both containing methods and variables, but they are different in many aspects.

Similar Reads

Differences between a Class and an Interface

The following table lists all the major differences between an interface and a class in Java language:...

Classes in Java

A class is a user-defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:...

Interface in Java

...