Java Object and Classes Tutorial
In this tutorial, we are going to learn about Java Objects and Classes. Java is an Object Oriented Programming language. So, everything in Java is associated with classes and objects.
What is an Object in Java
An object is an entity that has a state and behavior.
- State: Represents data (value) of an object.
- Behavior: Represents the behavior (functionality) of an object such as deposit, withdraw, etc.
- Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.
Real World Example:
A pen is an object that has state (color, name, etc.) and behavior (writing).
A car is an object that has state (color, brand, etc.) and behavior (accelerating, braking).
What is a Class in Java
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It contains:
- Fields
- Methods
- Constructors
- Blocks
- Nested class and interface
Syntax to declare a class:
class ClassName {
//fields
//methods
} Java Object and Class Example
In this example, we have created a Student class that has two data members id and name. We are creating the object of the Student class by new keyword and printing the objects value.
class Student {
int id = 1;
String name = "John";
}
class TestStudent {
public static void main(String args[]) {
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}