What is a class, an object and an instance in Java?
It has logical existence, i.e. no memory space is allocated when it is created.
It is a set of objects.
A class may be regarded as a blueprint to create objects.
It is created using class keyword
A class defines the methods and data members that will be possessed by Objects.
It has physical existence, i.e. memory space is allocated when it is created.
It is an instance of a class.
An object is a unique entity which contains data members and member functions together in OOP language.
It is created using new keyword
An object specifies the implementations of the methods and the values that will be possessed by the data members in the class.
If you have a program that models cars you have a class to represent cars, so in Code you could say:
Car someCar = new Car();
someCar is now an instance of the class Car. If the program is used at a repairshop and the someCar represents your car in their system, then your car is the object.
So Car is a class that can represent any real world car someCar is an instance of the Car class and someCare represents one real life object (your car)
however instance and object is very often used interchangably when it comes to discussing coding
The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.
Here an example of a class representing a Car:
public class Car {
int currentSpeed;
String name;
public void accelerate() {
}
public void park() {
}
public void printCurrentSpeed() {
}
}
You can create instances of the object Car like this:
Car audi = new Car();
Car toyota = new Car();
I have taken the example from this tutorial
A class is basically a definition, and contains the object's code. An object is an instance of a class
for example if you say
String word = new String();
the class is the String class, which describes the object (instance) word.
When a class is declared, no memory is allocated so class is just a template.
When the object of the class is declared, memory is allocated.