In this article, We try to understand the concept of Java Classes and Objects with an example. The key content of this article are-
(i) What is class and Object
(ii) Example of class and object
(iii) Difference between Class and Object
(i.a) Class In Java:
A class is an entity that determines how an object will behave and what the object will contain. In other words, it is a blueprint or a set of instruction to build a specific type of object. It provides initial values for member variables and member functions or methods.
(i.b) Object In Java:
An object is nothing but a self-contained component that consists of methods and properties to make a data useful. It helps you to determines the behaviour of the class.
i.e we say that "A class is a template for an object, and an object is an instance of a class". That's why class is called as logical entity, where object is physical entity. So simply, a class does not allocate memory space when it is created, on other hand, Object allocates memory space whenever they are created.
(ii) Example of class and object:
The OOPS concept is inspired by nature, and if we compare it with our real life world, if we consider what is the difference between Animal and set of animal type say tiger, lion, cat, cow etc.
Simply Animal we say class and tiger, lion, cat, cow are the instance of the animal, i.e we say object.
Example in code:
Animal class: is contain 3 member variable height,weight,color and 2 member function sleep() and eat().
class Animal { int height = 5; int weight =10; String color="black"; private void sleep(){ } private void eat(){ } }
Animal tiger=new Animal(); Animal lion=new Animal(); Animal cat=new Animal(); Animal cow=new Animal();
Comments
Post a Comment