Class & Object
Prepared By: Assadullah Mohammadi
In Java, classes and objects are foundational concepts of Object-Oriented
Programming (OOP). A class is a blueprint for creating objects, which are
instances of that class. A class defines the properties (attributes) and
behaviors (methods) that the objects created from it will have.
Class Definition
A class in Java is a template that defines the properties and methods for the
objects.
A class contains:
• Attributes (Fields): Variables that hold the data/state of the objects.
• Methods: Functions that define the behavior of the objects.
Object Definition
• An object is an instance of a class.
• It is created from a class and can access its attributes and methods.
Creating an Object:
Example: Class and
Object in Java
Let's create a simple Car class and
an object of that class.
Car Class Definition
Creating and Using a Car Object
Explanation of the Example
• Class Definition (Car):
• The Car class has three attributes: color, model, and year.
• It includes a constructor to initialize these attributes when creating a new Car object.
• The displayDetails method prints out the car's information.
• Creating an Object (myCar):
• In the main method, we create a Car object named myCar with the specified color, model, and year.
• We then call [Link]() to display the car's details.
Output of the Program
When you run this code, the output will be:
Summary
A class is a blueprint defining attributes and methods.
An object is an instance of a class, containing actual
data and methods it can perform.
In the example, Car is the class, and myCar is an
object of the Car class, initialized with specific values
and behavior defined by the class.