Class and Objects in OOPs

Class is a blueprint or model for the state and behaviour of a object.

Imagine as you want to program to find the speeds of cars Audi R8 and Benz A class with parameters distance travelled and time travelled given.

You may program codes separately for Audi and Benz cars to find their speed . Right?

If we want to find more number of cars speed, what we will do?

We will program codes again separately for every cars.

To avoid more lines and files of code, we can make a blueprint of common parameters and reuse the code. This blue-print or structure is known as class.

General Syntax

class class_name{

//methods or variables


The above is only a blueprint. You may have to create a object to make it work and use it.

Class name should start with a upper case letter and should not be any keyword.

When we create objects only, memory will be allocated.

Syntax for creating object,

new Class_name();

  • new is the keyword which is used to create a new object.
  • class_name() is the constructor which will discussed in the next topic.
  • To use the object later in the program or call any method or variable later in program we should assign this object to a variable of that class type.

Assigning object for later use

Class_name object_name=new Class_name();

object_name is only a reference variable, should start with a lower case letter and should not be any keyword.

You can access a method or variable inside class by using dot(.) operator with object_name.


class Cars{

float speed(int distance,int time){

int speed=distance/time;

return speed;



class Speed{

public static void main(String args[]){

Cars audi=new Cars();

Cars benz=new Cars();

float audispeed=audi.speed(1001,12);

float benzspeed=benz.speed(1101,12);

System.out.println("Audi's speed is "+audispeed);

System.out.println("Benz's speed is "+benzspeed);



Try In Editor

Values or methods that are assigned or executed through the object belongs to the particular object not the class.

Related topics

What is OOPs in Java ?