Posts

Showing posts with the label oops

Java classes and objects explained

In this blog post, I will be explaining the distinction between classes and objects. The most important thing to understand about a class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. public class Book {String bookName;String bookAuthor;} This is a very simple class called Book. This class keyword is used to declare a class.You can see here that I’ve declared some variables in the class. These variables are called instance variables or fields . This Book class acts as a template and we can create many books using this class. Now consider the following code snippet: public class Demo {public static void main(String args[]){Book book = new Book();}} The first line creates a new object of type Book and assigns it to the variable book . This object book will have its own copies of the variables bookName and bookAuthor. Each object contains its own copy of each instance variable defined by the class. A class acts like a templa...