Advertisement
Google Ad Slot: content-top
Java Class and Object
Java is an object-oriented programming language where the building blocks are classes, fields, constructors, methods, and objects. Let’s understand each of them in detail.
Class:
- A class is a blueprint for creating objects. It defines the fields (attributes) and methods (behavior) that an object will have.
Syntax:
class ClassName {
// Fields
// Constructors
// Methods
}
Fields:
- Fields are variables declared within a class. They define the properties or attributes of the class and its objects.
Syntax:
class ClassName {
DataType fieldName; // Field declaration
}
Constructor:
A constructor is a special method used to initialize an object. It is automatically called when an object is created.
- The name of the constructor must be the same as the class name.
- It does not have a return type.
Syntax:
class ClassName {
ClassName() {
// Constructor logic
}
}
Methods:
- A method defines a behavior or functionality of the class. Methods are blocks of code that perform specific tasks and can return a value.
Syntax:
class ClassName {
ReturnType methodName(Parameters) {
// Method logic
}
}
Object:
- An object is an instance of a class. It represents a specific entity that has its own state and behavior defined by the class.
Syntax:
ClassName objectName = new ClassName();
Multiple Objects:
You can create multiple objects of one class: