Classes and Objects in Java

 Let's explore the fundamentals of object-oriented programmingClasses and Objects — in Java, with clear explanations and code examples.


✅ What is a Class in Java?

A class is a blueprint or template that defines the structure and behavior (data and methods) that the objects created from it will have.

πŸ”Ή Think of a class as:

  • A design for creating objects.

  • It contains fields (variables) and methods (functions).

πŸ”Έ Syntax:


class ClassName { // Fields (variables) // Methods (functions) }

✅ What is an Object in Java?

An object is an instance of a class.

  • It represents a real-world entity.

  • Each object has its own state (fields) and can perform actions (methods).

πŸ”Έ Example:

If Car is a class, then myCar and yourCar are objects of that class.


✅ Java Program: Creating and Using a Class and Object


// Define a class class Student { // Fields (data members) String name; int age; // Method (behavior) void displayDetails() { System.out.println("Name: " + name); System.out.println("Age: " + age); } } // Main class public class Main { public static void main(String[] args) { // Create an object of Student class Student s1 = new Student(); // Set values s1.name = "Anjali"; s1.age = 20; // Call method s1.displayDetails(); } }

✅ Output:


Name: Anjali Age: 20

πŸ”Έ Key Terminologies

TermDescription
classKeyword to define a class
newKeyword used to create an object
ConstructorSpecial method used to initialize objects (explained below)
Dot operator .Used to access members of an object (e.g., object.method())

✅ Constructor in Java

A constructor is a special method that is automatically called when an object is created.

πŸ”Ή Example:


class Student { String name; int age; // Constructor Student(String n, int a) { name = n; age = a; } void display() { System.out.println(name + " is " + age + " years old."); } } public class Main { public static void main(String[] args) { Student s1 = new Student("Rahul", 21); // Object created with values s1.display(); } }

Output:


Rahul is 21 years old.

✅ Summary

FeatureDescription
Class            Blueprint that defines variables and methods
Object            Instance of a class
Constructor            Initializes object when created
new keyword            Used to create object
Dot . operator            Access fields and methods of object

Comments

Popular posts from this blog

Object Oriented Programming PBCST 304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Object Oriented Programming PBCST 304 Course Details and Syllabus

Type casting in Java