Object and Class in Java

Table of Contents

While learning about an Object Oriented Programming language, it is most important to understand that what is an Object is and how it relates with a Class.

So,What is an Object?

The object is any real-life entity that can be represented such as human, student, tree, car, etc.

An Object is decorated with the help of attributes and methods so that it can define the object with respect to the class.

For Example, Take a Sports-Car as an object. Now, its wheels, color, weight, size which is somehow fixed, are nothing but the attributes of it, but the features, speed, drives, all these are the methods that can define more accurately the object according to the class.

So,Now let’s understand that what is a Class?

A Class is a blueprint of an object.

For Example, If a motor vehicle is a Class, then motor-cycle, car, truck, bus all these are Objects, which are different from each other but share a couple of common features.

Now, let’s keep some important points in mind about the syntax of creating a class or an object.

class Sample//This is the name of the class 
  public static void main(String args[])
    //Anything inside it is a Block
  • So, the first observation over here is the declaration of the name the Class. Notice that it starts with a Capital letter, which is so as the name of Java file.


But you might ask a question that is it really important to name the Java file similar to the name of the Class?

However let me clear the point to you, that you can give the name of the class file anything you want and can compile it with that name only but while executing the file you must have to run it with the name of it class file, which is the exact name of the class that you have given.

Ok,let us understand the same with an example.

  • Create a Java file with the name of your selection,suppose,Hello.java.
  • Now, write the following code inside the Java file i.e. Hello.java
class Sample
  public static void main(String args[])
     System.out.println("Hello World!");//Statement always ends with semi-colon
  • Now ,while compiling it ,you need to write the following command:
javac Hello
  • But while executing the file, you need to execute it with the name of the class declared inside the Java file i.e.,
java Sample.java

Now ,let us have look of ,How to create an Object of the class.

So, create a class with the name of your choice, let say Sample.java, and write the following code inside it.

class Sample{
  int x = 5;//x is variable of Integer type

  public static void main(String args[])
    Sample obj = new Sample();//obj is the object of Class Sample

So,this is how we can create an object of a class.

Previous Operators in Java
Next Method in Java

Leave a Reply