DEV Community

S Sarumathi
S Sarumathi

Posted on

Class

A class is a user-defined data type that contains variables and methods.

Or even simpler:

Class = Variables + Methods

class Student {

    int id;
    String name;

    void display() {
        System.out.println(id + " " + name);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here:

  • Student → Class name

  • id, name → Variables

  • display() → Method

Creating Object from Class:

public class Main {
    public static void main(String[] args) {

        Student s1 = new Student();

        s1.id = 101;
        s1.name = "Ram";

        s1.display();
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

101 Ram
Enter fullscreen mode Exit fullscreen mode

Why Class is Important:
Without class:

  • No OOP

  • No Object

  • No Real-world modeling

Everything in Java revolves around Class and Object.

Top comments (0)