OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 1 : Classes Introduction
Unit - 2
Topic 1 : Introduction to Classes
In Java, a class is a user-defined data type that acts as a blueprint or template for creating objects. Once a class is defined, we can create multiple objects from it, each having its own data but sharing the same structure and behavior defined in the class.
Key Points:
-
A class defines what an object will contain (variables) and what it can do (methods).
-
An object is an instance of a class.
-
Instance variables store data for each object.
-
Methods define the operations that can be performed on the data.
General Form of a Java Class
Components of a Class:
-
Instance Variables: Data members of the class that hold values for each object.
-
Methods: Functions defined inside the class that operate on instance variables.
-
Members: Both instance variables and methods together are called members of a class.
Example: A Simple Class
In this example:
-
The class Box has three instance variables:
width
,height
, anddepth
(all of type double). -
It has one method,
volume()
, that calculates and prints the volume of the box using the instance variables.
Creating and Using Objects
Once we have defined a class, we can create objects from it:
Explanation:
-
Box myBox = new Box();
→ Creates a new object of typeBox
. -
myBox.width = 10;
→ Assigns values to the object's instance variables. -
myBox.volume();
→ Calls thevolume()
method to calculate and display the volume.
Key Notes about Classes in Java
-
A class can have multiple objects, each with independent values for its instance variables.
-
Methods in a class can access and modify the instance variables.
-
Classes help in achieving Object-Oriented Programming (OOP) concepts like encapsulation, inheritance, and polymorphism.
Example Program on Java Classes
Explanation:
-
Class Definition:
-
The
Box
class has three instance variables:width
,height
, anddepth
. -
It contains a method
volume()
to calculate and print the volume.
-
-
Creating Objects:
-
Box box1 = new Box();
creates an objectbox1
of typeBox
. -
Box box2 = new Box();
creates another objectbox2
.
-
-
Assigning Values:
-
Each object has its own set of instance variables.
-
We assign values to them separately.
-
-
Calling Methods:
-
box1.volume();
calls the method for the first object. -
box2.volume();
calls the method for the second object.
-
Sample Output:
Comments
Post a Comment