Java

What Is a Class Keyword In Java

In Java, a class is created with the class keyword. Variables, methods, etc. are all contained in classes. Without a class, Java code cannot be executed.

Notes:

  • The class name that includes the main function must match the file where the Java code is located.
  • Class names are distinct and cannot be used again inside the same package.
  • Multiple classes may exist in a single Java file, but the file name must correspond to the class’s main method.

Example of class keyword

Here, a class is being created using the term class. There is a method and a variable in this class. By creating an object of this class as shown below, you can have access to these:

//class name is "JavaExample"
public class JavaExample {
  int i = 101;
  public void hello(){
    System.out.println("Hello");
  }

  public static void main(String[] args) {
    //creating an object of JavaExample
    JavaExample obj = new JavaExample();
    //accessing class variable
    System.out.println(obj.i);
    //accessing method of the class
    obj.hello();
  }
}

Output:

101
Hello

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button