Classes and Objects in Java
Object oriented programming is all about Classes and Objects, so we have to get rid of putting all code in main() method unlike procedural programming.
First lets look at the difference between Class and Object.
A Class is not an Object, it is object constructor or you can call it as “blueprint for an Object”.
Class instruct to JVM how to construct an Object of that particular type. Each object made from particular class can have different values and variables. As an example lets assume there is a class called Car, it can have multiple objects each Car might have its own color, make, engine capacity and model.
An object is an instance of Class and it also can defined as “one entry in your address box”
For example let’s assume there is a Class called Car, there may different types of cars. Therefore we can have instances like Sedan, Convertible, Coupe, SUV and Crossover from Car class.
We have created a Class and fewObjects from that class. Now let’s look at how to access objects variables and methods with dot operator(.)
In java when object is created, it goes into memory area called “Heap”, but the thing is, this in not ordinary memory Heap. Java memory heap called as “Garbage-Collectible Heap”.
When creating an object, java allocates memory space on heap based on how much that particular object is needed. As an example let’s assume there is an object with 10 instance variables, and there is another object with 2 instance variables. So it’s pretty clear that object with 10 instances need more memory space. Have you ever wondered how we can gain that memory space again and how we can get object out from the heap when you no longer need it ?. The simple answer is you don’t need to manage memory manually, java manages that memory for you.
If JVM notice that any object can no longer be used, that particular object is eligible for garbage collection. When memory is running low, garbage collector is clear the memory space by throwing out unreachable objects. Therefore you don’t need worry much about the memory management in Java unlike the languages like C++.
Hope this article will be helpful for you.
Thank You!
Reference
Head First Java 2nd Edition by Kathy Sierra & Bert Bates.