Java Class


Class

A class can be defined as a template that describes the behaviors and states of a particular entity. Everything in java is encapsulated under the classes. It is known as the core of the Java language. To declare a class, a class keyword is used. It contains both data and methods that operate on that data. Data or variables defined inside a class are called instance variables, and the code that operates on this data is known as a method. Therefore, the instance variables and methods are known as class members. A class can consist of fields, methods, constructors, and blocks

Syntax:

Class className{
fields;
methods;
}

The programming language java is an object-oriented language. Like in all programming languages, a Class is similar to an object constructor, or we can say a "blueprint" for constructing objects.
In java, the class should always begin with an uppercase first letter, and that the title of the java file should match the name of the class.

Using Multiple Classes in Java

The programming language java is an object-oriented language. Like in all programming languages, a Class is similar to an object constructor, or we can say a "blueprint" for constructing objects.
In java, the class should always begin with an uppercase first letter, and that the title of the java file should match the name of the class. Using Multiple Classes in Java We can also create an object of a class and obtain it in a different class. However, it is usually practiced for greater organization of classes (one class contains every attribute and method, whereas the other class contains the main() method (code to be performed)).
Always remember that the name of the java file should match the name of the class.

In java, A class can contain things like:

  • The Fields
  • The Methods
  • The Constructors
  • The Blocks
  • The Nested class and interface

Example No.1:

Com.knowledge2life public class Main { String x= "Knowledge2life"; public static void main(String[] args) { Main myObj = new Main(); System.out.println(myObj.x); } }

OUTPUT:

Knowledge2life

Example No.2:

Com.knowledge2life public class Main { String x= "Knowledge2life"; public static void main(String[] args) { Main myObj1 = new Main(); Main myObj2 = new Main(); System.out.println(myObj1.x); System.out.println(myObj2.x); } }

OUTPUT:

Knowledge2life
Knowledge2life