Java Classes and Objects
π§ What is a Class?
A class in Java is a blueprint or template used to create objects. It defines properties (variables) and behaviors (methods) that the object will have.
Think of a class like a car designβit defines how cars are made, but itβs not a real car itself. The actual cars built from that design are the objects.
β Syntax of a Class:
π§ What is an Object?
An object is an instance of a class. It holds real values for the fields defined in the class and can use the class methods.
You create (instantiate) objects using the new
keyword.
π§ͺ Example:
π Output:
πΈ Fields, Methods, and Access:
-
Fields: Variables inside a class.
-
Methods: Functions that define behavior.
-
Access: Use the dot operator (
.
) to access fields and methods from an object.
π§Ύ Important Points:
-
A class is not memory-consuming until objects are created.
-
Objects have state (field values) and behavior (methods).
-
You can create multiple objects from the same class.