Friday, August 19, 2016

Concept of Classes and Object in JAVA

A class is a model or blueprint for creating similar type of objects.Class contain the 
variable and methods. To understand a class ,take a pen and paper and write down all the 
properties and actions of any Person. So it is called a CLASS because its contain the 
properties and method or function of generic person.

Now we can create various objects with the use of similar kind of properties and methods of 
Class Person.

For example: SITA, DEV and KARAN are the objects of the Class Person that can have the same 
properties and functions which defined in Person Class.




















/* ##################  Person Class  #############################*/

// class keyword is used to declare a Class

public class Person {
 
 // Properties -instance Variables
 String Name;
 int Age;
 int PasspotNo;
 
 //actions -Methods
 void Dancing()
 {
 System.out.println("I am Dancing and My name is "+Name);
 }
 
 void Running()
 {
 System.out.println("I am Running and My Age is "+Age);
 }

}
So this is the way in JAVA we define the Class and you can say that this is the blueprint 
for Creating the Similar Kind of Objects.

To use a class, we should create an object to the class.Following syntax is used to create 
the Object in Java.

ClassName objectname = new ClassName()

So to Create the SITA object to Person Class, we can write as:

Person SITA = new Person();

Here "new" is an operator that created the object to Person class. Once we create the
Object of the Class a JVM provides the reference number or copy of the class to the object 
or variable for use.

Here SITA is object or variable that stores the reference number of the object returned by 
JVM.

Now below code will explain you how we create the object of Person class and How we use it.
Once you write object after creation and put the dot then you will see all the variables 
and Method list that has been define in Person Class.

Look into the below screenshot. Now you can use those


public class CreateObjectPersonClass {

 
 public static void main(String[] args) {
  
  //Creating object obj1 of Person Class with the use of new operator
  Person obj1 =new Person(); 
  
  //Assign the Value to instance Variables
  obj1.Name ="SITA";
  obj1.Age =24;
  obj1.PasspotNo= 123456;
  
  //Calling the Instance Methods
  obj1.Dancing();
  obj1.Running();
  
 }

}
Output:
I am Dancing and My name is SITA
I am Running and My Age is 24

Thanks...if you feel that this is fruitful information for you then please like 
this and give your feedback.


No comments:

Post a Comment