Thursday, August 13, 2015

Class and Object in Java

Class

          A class is a user defined data type. a class encapsulates a group of logically related data items and functions that works on them. In Java, The data items are called fields and the functions are called methods.
         Encapsulations is a machine that binds together code and data and the data it manipulates and keeps both safe from outside interface and it misuse.


        Basic Structure of Class definition:

class classname                                      //class definition
{
   type variablename;                               //fields declaration
   type methodname(parameters list)                //method declaration
    {
      method-body;
    }
}






  • A class is defined using the class keyword where the c of class is in small case.
  • Once a class is defined, Instance (Object) of the class can be created and each instance can have different copy of instance variables (fields).
An example of class book:




class Book                                      //class definition
{
   String name;
   String authorname;
   float price;                                    //fields declaration
   String displayname()                           //method declaration
    {
      System.out.println("Name of the book is   :"+name);
      System.out.println("Name of the Author is :"+authorname);
      System.out.println("Price of the book is  :"+price);
    }
}