DEV Community

Cover image for Class in Java::
MANOJ K
MANOJ K

Posted on

Class in Java::

1. class:

  • A class is a blueprint or template used to create objects.
  • It defines the properties (variables) and behaviors (methods) that the objects created from it will have.

2.Use the class keyword:

  • A class must be declared using the class keyword.
class MyClass {
}

Enter fullscreen mode Exit fullscreen mode

3.Class name rules:

  • The class name must start with a letter (A–Z or a–z).
  • It cannot start with a digit.
  • It must not contain spaces.
  • Special characters are not allowed except _ and $.
  • Java reserved keywords cannot be used as class names.

4.Naming convention:

  • By Java convention, the class name should start with a capital letter, and if it contains multiple words, each word should start with a capital letter.
class StudentDetails
Enter fullscreen mode Exit fullscreen mode

5.Curly braces are mandatory:

  • The body of a class must be enclosed within curly braces { }.
class Car {
    // fields and methods
}

Enter fullscreen mode Exit fullscreen mode

6.One public class per file:

  • A .java file can contain only one public class.

7.File name rule:

  • If a class is declared as public, the file name must be the same as the public class name.
public class Student {
}

Enter fullscreen mode Exit fullscreen mode

8.Access modifiers:

  • A class can have an access modifier like public or no modifier (default).
  • Top-level classes cannot be private or protected.

9.main() method is required to run:

  • To execute a Java program, the class must contain the main() method.
public static void main(String[] args) {
}

Enter fullscreen mode Exit fullscreen mode

10.Multiple classes in one file:

  • Multiple classes can be defined in a single file, but only one can be public.

Top comments (0)