Classes and Objects in JAVA
Classes and Objects in JAVA
UNIT-2
What are Java Classes?
A class is a blueprint from which individual objects are created (or, we can say a
class is a data type of an object type). In Java, everything is related to classes and
objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.
For example, if you want to create a class for students. In that case, "Student" will
be a class, and student records (like student1, student2, etc) will be objects.
We can also consider that class is a factory (user-defined blueprint) to produce
objects.
Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside
any method, with the static keyword.
Creating (Declaring) a Java Class
To create (declare) a class, you need to use access modifiers followed
by class keyword and class_name.
Syntax to create a Java class
Use the below syntax to create (declare) class in Java:
access modifier class class_name {
data members;
constructors;
methods;
...;
}
Example of a Java Class
In this example, we are creating a class "Dog". Where, the class attributes
are breed, age, and color. The class methods are setBreed(), setAge(), setColor(),
and printDetails().
// Creating a Java class
class Dog {
// Declaring and initializing the attributes
String breed;
int age;
String color;
Note: parameters are optional and can be used while you're using constructors in the class.