What is the difference between Class and Object in Java?

UPDATED: 31 May 2015

Developer always gets confuse, when they face this question. They creates class and object in their day to day life. However, they don't know the concept behind it. Lets understand the difference between them.

Class
A Class defines a new data type and it is template for an Object (A Class is data type and can be used to create an Object of that data type.). A class can be declared using class keyword.


Book (An example of Class)
Following class defines common template(class) for Book. That can be used to create an Object of Book.
public class Book{
   String name;
   String author;
}

Object
Object is instance of Class. You can create Object using new keyword. When you create an Object using new keyword then it allocates memory for an object at runtime and returns reference to it.


Example of Object
You can create as many Objects of Book. Each Object hold its own copy of variables defined in Class Book.
Book objBook = new Book();

Book objJavaBlackBook = new Book();
objJavaBlackBook.name = "Java Black Book";
objJavaBlackBook.author = "James Gosling";

Book objFiftyShadesofGrey = new Book();
objFiftyShadesofGrey.name = "Fifty Shades of Grey";
objFiftyShadesofGrey.author = "E. L. James";

Book objBriefHistoryofTime = new Book();
objBriefHistoryofTime.name = "A Brief History of Time";
objBriefHistoryofTime.author = "Stephen Hawking";
As you can see in above example we have three different objects of Book and each hold different values for name and author. Here Class Book used as a template for different types of Book.

0 comments :