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.
- Classes are defined using the class keyword. A class typically includes a constructor, methods, and can extend other classes.
- Classes are template for creating the object.
Animal classes
Basic Parts of a Class
- Class Definition: This is like creating the blueprint.
- Constructor: This is a special function that sets up new objects based on the blueprint.
- Methods: These are functions that describe what the objects can do.
Using the Class
When you have a class, you can use the class to create objects:
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);
Creating an Object
Using the blueprint, we can create a car:
const myCar = new Car('Toyota', 'Corolla');
myCar.describe();
Output: This car is a Toyota Corolla.
Object
A javaScript object is an entity having state and behavior (properties and method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don’t create class to get the object. But, we direct create objects.
How to create Object
const object_name = {
key_1: value_1,
key_2: value_2,