Java Class and Object

In this tutorial we will learn class and object in detail

So, drink a glass of water and start. It is a very important article so read carefully

Class:

class is nothing but it is a group of objects of similar type. Let’s understand with an example

suppose Cars is a class.  and Audi car BMW cars, Lamborghini car is the object of Cars class.
Class contain method and common characteristics (variables) of object

So here common characteristics is

  • No. of seats in the car
  • Speed of car 🚙 
  • color of car
  • price of car

they all are common characteristics in all cars (they are data members of the class)

by the using of these characters we can create new car

how to declare a class

syntax:

class ClassName {
   // variables
   // methods
}

See this example :

class Cars {

  // instance variable
  int seats;
  int speed;
  String color;
  int price;

  // method
  public void buildcar() {
  	System.out.println("your car is ready"+ seats + speed + color + price)
  }
}

here Cars is a class. in the body of the class seats, speed, color, price is variable

and buildcar is method of Cars class

Object:

Object is an instance of class which determines the behavior of class.

A Object of class can access any class variable and method of that class

Object can be a data structures or a function

How to create object of class

className object = new className();

Example Create a object of a cars class

// here bmwcar is an object
Cars bmwcar = new Cars();
// here audicar is an object
Lamp audicar = new Cars();

How to access member of a class:

As I told object can access member of class and assign a new value to it

. dot operator is use to acess member of a class

For example: Let’s access buildcar method of a  Cars class

// create object
Cars bmwcar = new Cars();

// access method buildcar()
bmwcar.buildcar();

let’s see a complete example use variable and method of Cars class

class Cars {

  // instance variable
  int seats;
  int speed;
  String color;
  int price;

  // method
  public void buildcar() {
  	System.out.println("your car is ready \n"+"number of seats" +
  	" = "+seats+"\n"+"speed of car"+" = "+speed+"\n"+"color of car"+" = "+color+"\n"+"price of car"+" = "+ price);
  }
}

public class Main{

     public static void main(String []args){
       Cars bmwcar = new Cars();
  
        // call methods 
         bmwcar.seats = 2;
	bmwcar.speed = 650;
	bmwcar.color = "blue";
	bmwcar.price = 5000000;

        bmwcar.buildcar();

     }
}

output:

your car is ready 
number of seats = 2
speed of car = 650
color of car = blue
price of car = 5000000


SHARE THIS PAGE





Important Link