Class and Object are fundamental and vital principles of Object-oriented programming (OOPs).
A class is a blueprint or prototype from which objects are created.
It’s a logical entity and not a physical entity.
We can create any number of objects using one class.
An object is an instance of a class.
It’s a real world entity like Table, Book, Paper, and etc.
It’s a physical entity.
Objects can be created any number of times using a single class based on requirements.
We can easily relate class and object with our real-life examples. Let’s consider you are going to build a house. For that, you will first ask some engineer to put a plan for the house. The engineer analyses various criteria like Land size, number of floors, etc. Then, the engineer gives you the best blueprint or plan for the house. This can be related to our Class in OOPs.
Using the blueprint or plan, you can build a home. Here, the house can be considered as an object which is a physical entity.
Let’s consider a phone example if you are going to manufacture multiple brand phones like iPhone and Vivo.
Here, the blueprint for those phones are defined in Phone class. The properties can be price, screen size, battery capacity, etc.
Each model has its properties
iPhone 8 properties are Price=60,000RS, Battery Capacity=1,821mAh, OS=ios 12
Vivo V9 properties are Price=17,000RS, Battery Capacity=3260, OS=Android 8.1
Here, class is the keyword. It should in lowercase (case sensitive). Phone is the class name. The class name can be anything it should follow some standards. You can define the class variables and methods inside the { and }.
Class can have instance variables like os, price and batterCapacity.
It can have Constructors, Getter and Setter Methods.
class Phone { //Data members String os; double price ; int batterCapacity; //Constructor public Phone(String os, double price, int batteryCapacity) { this.os=os; this.price=price; this.batteryCapacity=batteryCapacity; } //Functions public double getPrice() { } public int getBatteryCapacity() { } }
There are three types of variables like Local, Instance and Class Variables. In the above example, we have used instance variables.
Instance variables are declared inside a class but not inside the methods or constructors.
Here, os, price and batterCapacity are the instance variables. Every object can have their specific properties in instance variables.
Constructors are special methods which are used to initialize objects. The constructor name and class name should be the same.
Here, public Phone(String os, double price, int batteryCapacity) is the constructor.