Classes in Java
Classes are considered blueprints for an object. It consists of the behavior, and attributes of an object. Classes and objects are the basis of all object-oriented programming concepts. Class doesn't occupy any memory until it is instantiated. The class contains different methods and different variables in it. Generally, a class in java contains methods, variables, constructors, and nested classes. A class represents a set of properties followed by all objects in common. A class is generally enclosed in {}.
Syntax
Below is the syntax to be followed to create a class in java:
Access modifier: Accesses modifiers are private, public, default, and protected.
- Constructor: Constructors are special methods that are named the same as the class name and it is invoked whenever an object of the class is created. It is generally used for the initialization of variables
- Data members/variables: A class can consist of data members of different data types.
- Methods: A class consists of different methods which have different properties to be implemented.
- Nested class: A class in itself can consist of a nested class.
- Interface: This keyword when used while initiating a class is helpful for multiple inheritances in java.
Objects in Java
It represents real-time entities. It occupies memory. It is instantiated using a keyword new in java. It consists of state, behavior, and identity. Identify represents the unique name that is given to the object which is created. Behavior consists of the methods of the object. The state of the objects represents the attributes of the class, it basically represents the properties of the class. There are many ways in creating an object of a class.
Example
Below is an example of implementing both class and object in java:
The output obtained is as follows:
Conclusion
Classes and objects are considered building blocks of object-oriented concepts. Class is the blueprint of the object which has to be created. It consists of methods, data members, nested classes, etc. Object consists of a state, behavior, and identity of its own.