Java – Class and Object

  • Objects are anything that exists in the world. A Class is a blueprint to develop objects.
  • If you consider creating objects like chair, table, cupboard, then you need to create class called Furniture. Similarly by using Person class, we can create objects like Elaya, Dara, Bharath etc.

  • Class contains variables and methods.
  • Variables are attributes or peoperties.
  • Method perform the functions or actions.

A Class looks like


Example program to understand objects :

public class Person{ 
 String name;
 int age;
 public void displayMsg(){
   System.out.println("Im " + name );
   System.out.println("Im " + age + " years old");

public class UsePerson{ 

 public static void main(String[] args) {
   // Create an object of type Person and referred by a variable personOne.
   Person personOne= new Person(); = "Dara";       
   personOne.age = 20;


C:> javac
C:> java UsePerson
Im Dara
Im 20 years old

We have two classes in a same source file. Then, which name should we use as a file name ?

You have to use the name of the class containing main() method. so we save the above source file as

The main() method:

A Java application can have any number of classes but any one class should contain a main() method. During runtime, the JVM will search for the main() method and start executing the statements in main() method.

The syntax is 

public static void main(String [] args)
// statements

Then what about public, static and void. That we will discuss in the remaining chapters.

The new() operator

Using Person class, you can create any number of objects using new() operator.The syntax is

classname objectname = new classname();

To create an object for Person class, we use

Person personOne= new Person();

new Person() will create a object of type Person.
personOne is a variable name to refer object of type Person

The dot operator;

The variables and methods of Person class is available to all the objects of Person class. Those variables and method are accessed by using dot operator.

The name variable of personOne object is specified by = “Dara”;

similarly, the age variable of personOne object is specified by personOne.age

personOne.age= 20;

Prev                                                                                                                                         Next