Java Classes and Objects


    Introduction to Java Classes and Objects

    •  Java is an Object-Oriented Programming Language (OOP). At the heart of Java lies the concept of classes and objects, which help us create real-world entities in code.

    What is a Class in Java?

    •  A class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that the objects created from the class will have.
    •  Think of a class like a car design, and each individual car is an object made using that design.

    Syntax of a Java Class

    java

    class ClassName {

     // fields (variables)

       // methods

    }

    Example:

    java

    class Car {

    String color;

      int speed;

        void drive() {

       System.out.println("The car is driving.");

      }

    }

    Components of a Class

    •  Fields: Variables to hold data (e.g., name, age, speed).
    •  Methods: Functions that define behavior.
    •  Constructors: Special methods used to initialize objects.
    •  Blocks: Initialization blocks or static blocks.
    •  Nested classes: Classes inside a class.

    What is an Object in Java?

    •  An object is a real-world entity created from a class. It has state (data) and behavior (methods).
    •  Example: A dog is an object of class "Animal".

    How to Create an Object in Java

    Syntax:

    java

    ClassName obj = new ClassName();

    Example:

    java

    Car myCar = new Car();

    Here, myCar is the object, and Car() is the constructor being called.

    Accessing Class Members using Objects

    java

    myCar.color = "Red"; // Accessing field

    myCar.drive(); // Calling method

    Real-life Analogy of Class and Object

    Class = "Fruit"

    Object = "Apple", "Banana", "Mango"

    Each object has unique features, but they all follow the same structure defined in the "Fruit" class.

    Java Program using Class and Object

    java

    class Student {

      String name;

        int age;

         void display() {

         System.out.println("Name: " + name);

         System.out.println("Age: " + age);

       }

    }

    public class Main {

      public static void main(String[] args) {

        Student s1 = new Student();

        s1.name = "Ravi";

        s1.age = 21;

        s1.display();

       }

    }

    Output:

    makefile

    Copy

    Edit

    Name: Ravi

    Age: 21

    Constructors in Java

    •  A constructor is a special method used to initialize objects. It has the same name as the class and no return type.

    Default Constructor

    java

    Copy

    Edit

    class Animal {

       Animal() {

        System.out.println("Animal created");

      }

    }

    When we create Animal a = new Animal();, the message prints.

    Parameterized Constructor

    java

    Copy

    Edit

    class Book {

      String title;

        Book(String t) {

       title = t;

    }

    void show() {

         System.out.println("Title: " + title);

       }

    }

    Constructor Overloading

    •  Having multiple constructors with different parameters.

    java

    Copy

    Edit

      class Box {

         int length;

         Box() {

       length = 10;

    }

    Box(int l) {

        length = l;

       }

    }

    ‘this’ Keyword

    Used to refer to the current class instance.

    java

    Copy

    Edit

      class Pen {

         String color;

          Pen(String color) {

        this.color = color;

      }

    }

    Method inside Class

    •  You can write multiple methods inside a class to define its behaviors.

    java

    Copy

    Edit

      class Dog {

        void bark() {

        System.out.println("Barking...");

    }

      void sleep() {

        System.out.println("Sleeping...");

      }

    }

    Object Initialization Techniques

    •  Using reference variable
    •  Using method
    •  Using constructor

    Static vs Non-static Members

    •  Static: Belongs to the class
    •  Non-static: Belongs to the object

    java

    Copy

    Edit

      class Demo {

        static int count;

      int id;

    }

    Memory Allocation of Objects

    •  Heap: Where objects are stored
    •  Stack: Stores references and primitive values

    Garbage Collection in Java

    •  Java automatically removes unused objects using Garbage Collector.

    java

    Copy

    Edit

    obj = null; // Eligible for GC

    Anonymous Objects

    java

    Copy

    Edit

    new Car().drive();

    Used when we don't need to reuse the object.

    Object as Method Parameter

    java

    Copy

    Edit

       void display(Student s) {

      System.out.println(s.name);

    }

    Returning Object from Method

    java

    Copy

    Edit

      Student getStudent() {

        Student s = new Student();

      return s;

    }

    Nested Classes

    •  Class defined inside another class.

    java

    Copy

    Edit

    class Outer {

      class Inner {

          void msg() {

          System.out.println("Hello from Inner class");

        }

      }

    }

    Complete Example Program

    java

    Copy

    Edit

    class Employee {

    int id;

    String name;

      Employee(int i, String n) {

        id = i;

       name = n;

    }

      void display() {

         System.out.println(id + " " + name);

       }

    }

    public class Main {

       public static void main(String[] args) {

         Employee e1 = new Employee(101, "Amol");

            Employee e2 = new Employee(102, "Ravi");

           e1.display();

        e2.display();

       }

    }

    Conclusion

    Java classes and objects form the foundation of OOP in Java. A class defines the structure, and an object brings it to life. With constructors, methods, and memory management, Java provides a powerful way to model real-world problems through code.


    Also Read:

    Post a Comment

    0 Comments