In Java everything is encapsulated under classes. Class is the core of Java language. It can be defined as a template that describe the behaviors and states of a particular entity.
In Java, class is declare using class keyword. A class contain both data member and methods that operate on that data. The data or variables defined within a class are called instance variables and the code that operates on this data is known as methods.
Thus, the instance variables and methods are known as class members.
We can create a class in Java using the class keyword.
Syntax:
class ClassName {
// dataMember
// methods
}
class Simple {
// dataMember
int number = 3;
// method
void message()
{
System.out.println("Hi i'm method in a class Simple")
}
}
In the above example, we have created a class named Simple. It contains a dataMember number and a method named message().
Object is an instance of a class. An object in OOPS is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful. When you send a message to an object, you are asking the object to invoke or execute one of its methods as defined in the class.
In a simple word object is a real world entity which have predefined attributes and its beheviour. It has a physical thing as well as abstract in nature.
Here is how we can create an object of a class.
Syntax:
ClassName ReferenceVariable = new ClassName();
class Simple {
int x = 10;
public static void main(String[] args) {
Simple obj = new Simple();
System.out.println(obj.x);
}
}
Output:
10
We can also create multiple objects of one class. Here is the example of multiple object creation.
class Simple {
int x = 10;
int y = 20;
public static void main(String[] args) {
Simple obj1 = new Simple();
Simple obj2 = new Simple();
System.out.println(obj1.x);
System.out.println(obj2.y);
}
}
Output:
10
20