Q:- What is Class?
In Java, a class is a blueprint or a prototype from which objects are created. A class encapsulates data for the object and methods to manipulate that data. It defines the properties (attributes) and behaviors (methods) that the objects created from the class can have.
Q:- What is object?
In Java, an object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created. Objects are the fundamental units of object-oriented programming and represent real-world entities. An object consists of:
- State: Represented by attributes or fields (variables).
- Behavior: Represented by methods (functions).
- Identity: A unique identifier, usually the memory address where the object is stored.
Difference between object and class
Feature | Class | Object |
Definition | Class is a blueprint or template from which objects are created. | Object is an instance of a class. |
Class is a logical entity. | Object is a physical entity. | |
Class is a group of similar objects. | Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc. | |
Keyword | Class is declared using class keyword | Object is created through new keyword |
Feature | Class | Object |
Declaration | Declared once | Created as needed |
Attributes & Methods | Defines structure and behavior | Has actual values and can perform behaviors |
Memory Allocation | No memory allocation | Memory is allocated |
Example | public class Car { … } | Car myCar = new Car(…); |
Interview Questions
Question 1:- What Is a Constructor and How Do You Use It?
Answer: A constructor is a special method that is automatically called when an object is created. It is
used to initialize the object’s attributes.
Question 2:- What Is the Purpose of the new Keyword in Java?
Answer: The new keyword is used to create new objects in Java. It allocates memory for the object and
initializes it by calling the constructor.
Person p = new Person(); // Creates a new Person object
Question 3:- Write a simple Java class Calculator that has a method add which takes two integers and
returns their sum.
Answer:
public class Calculator {
// Method to add two numbers
int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator(); // Creating an object of Calculator
System.out.println(calc.add(5, 3)); // Output: 8
}
}