CLASSES AND OBJECTS — JAVA
What is class and object in java?
In simple language we can say class is a model in which we define the variables and methods which is used to objects and not physically exist , Where as an object is anything that exists physically having the properties and actions defined in class .
Lets Know More about Classes and Objects with real life example
Let us consider a Person whose name is Lakshay. Here Lakshay is object because it physically exist and have the properties like name, age, sex etc. these properties in programming world represent as variables . Now Lakshay also perform some action like walking, talking, eating etc. these actions are called as methods(functions),So the object contains the variables and methods.
Now think any other object like Raju, Ramesh, Ravi, Anjali they all are person and have also the same properties and actions, hence the group of such object is called as Class . From here we come to know that the Class is a group name (Person as example used here) but does not exit physically.
How classes and objects work in JAVA?
Now here we know how to create the class and object in java programs.
How to define a class in java?
A class is define in java by using the CLASS keyword .
The general form of class is as:-
Lets take a simple example how for class in java,
\\properties( instance variables) of the person
\\ action(method) performed by the person
System.out.println(“Hello my name is” +name+ ”and my age is ”+age);
Till we have created the class/group of persons but to add the persons in we have to access the properties and the actions of the class for that we have to create the object. Now let see how to create the object.
How to create a object in java?
To create and object in java we need a class form which we can use the variables and methods .
Syntax for creating the object:
Classname Objectname = new classsname();
How to access the properties and method of class in java?
To access the properties of class we define as
Now lets take an example how the object is create, considering the class Person defined above.
\\ creating the object of class person
Person person1 = new Person();
\\ access the properties as
person1.name = “Lakshay saini”;
person1.age = “18”;
\\access the method
Object are created by JVM on heap memory that’s why we use “new” which tells the JVM to allot the memory for object of the class.