A class is a blueprint for creating various objects. Objects are an instance of a class. For example, suppose we have a class named Student. John, Lisa etc. can be considered as objects of the class Student. Basically, objects are any real life physical entity - cars, animals, people, books - they all are objects. These objects belong to a certain class which defines their behaviour and states. A car is a vehicle with 4 wheels (state) and can move certain kilometers (behaviour). A person has a name, an id, some height, weight (states) and a person can walk, eat, sleep, work (behaviour). Therefore, we say that a class is a blueprint of objects.
Declaring a class in Java
Here's how a class is declared in Java :
public class ClassName{
data_type data1;
data_type data2;
.
.
.
data_type dataN;
return_type method1(parameter_list){ }
return_type method2(parameter_list){ }
.
.
.
return_type methodM(parameter_list){ }
}
Here data1, data2 etc. are known as instance variables. We can make them class variables by declaring them as static, using the static keyword. For example, static int variable1;
These variables define the state of the object. They are instantiated when an object is created.
Next, we have the class methods. Class methods are simply functions that belong to the class that they are defined in. They describe the behaviour of the object. They may be used to modify an object's state, display the current state or make inferences regarding the object on the basis of its state.
An example of a class is as follows :
public class Student{
int sId;
String sName;
float sMarks;
char grade;
void getData(int id, String name, int marks)
{ sId = id;
sName = name;
sMarks = marks;
grade = calcGrade(marks);
}
char calcGrade(int marks)
{ if(marks >= 90)
grade = 'A';
else if (marks >=80)
grade = 'B';
else if (marks >= 70)
grade = 'C';
else grade = 'D';
return grade;
}
void printData()
{
System.out.println("ID : "+sId+"NAME : "+sName+"GRADE : "+grade);
}
Now, we have to create objects for our class. This can be done using the new keyword. This is how we would declare an object :
Student s1 = new Student();
To initialise values, we can write
To print the state of our object, we write