Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are Classes and Objects in Java? Java में Classes और Objects क्या हैं?

Answer
// Class Definition
public class Student {
    // Attributes (Member Variables)
    private String name;
    private int rollNumber;
    private double gpa;
    
    // Constructor
    public Student(String name, int rollNumber) {
        this.name = name;
        this.rollNumber = rollNumber;
        this.gpa = 0.0;
    }
    
    // Methods
    public void study() {
        System.out.println(name + ' is studying');
    }
    
    public void setGPA(double gpa) {
        this.gpa = gpa;
    }
    
    public double getGPA() {
        return gpa;
    }
}

// Creating Objects (Instances)
public class Main {
    public static void main(String[] args) {
        // Object creation
        Student student1 = new Student('John', 101);
        Student student2 = new Student('Jane', 102);
        
        // Using objects
        student1.study();
        student1.setGPA(3.8);
        System.out.println('GPA: ' + student1.getGPA());
    }
}

// Key Differences:
// Class: Blueprint, template, logical entity
// Object: Instance of class, physical entity created in memory
// One class can have multiple objects
// Objects consume memory, class does not
Class: Blueprint (logical)
Object: Instance of class (physical)

Class बनाते हैं, objects create करते हैं।
एक class के multiple objects बना सकते हैं।

Was this answer clear?