Classes and Objects in JAVA

Classes and Objects in JAVA

Class :- A Class is a blueprint from which individual objects are created. A class is a template and when a class is declared no memory is allocated to it.

Object :- An object is an instance of a class which consists of identity, state and behavior.

Example, Let us say we have a class called Mobile. Let us say that it has various attributes like model, color, dimensions, ram & rom. We know that there are different brands in mobiles like apple, samsung, asus and lenovo. So these brands form the objects as they all are instances of the class Mobile and will have different values for the attributes given.

Class Mobile{}

Mobile iphone = new Mobile();  // Creating an object or an instance(iphone) of class Mobile

Let us write a program for the example given above, representing class and objects in java.

Program

import java.util.*;

class Mobile
{
	String model,dimension,ram,rom;
}

class Main
{
	public static void main(String args[])
	{
		//Creating an object(iphone) or instance of class Mobile 
		Mobile iphone = new Mobile();
		iphone.model = "iphoneX";
		iphone.dimension = "5.5 inches";
		iphone.ram = "3GB";
		iphone.rom = "64GB";
	
		System.out.println("\t\tBrand APPLE");
		System.out.println("Model: "+iphone.model);
		System.out.println("ScreenSize: "+iphone.dimension);
		System.out.println("RAM: "+iphone.ram);
		System.out.println("ROM: "+iphone.rom);

		//Creating an object(asus) or instance of class Mobile
		Mobile asus = new Mobile();
		asus.model = "Zenfone 5z";
		asus.dimension = "6.3 inches";
		asus.ram = "6GB";
		asus.rom = "64GB";
		System.out.println("\t\tBrand ASUS");
		System.out.println("Model: "+asus.model);
		System.out.println("ScreenSize: "+asus.dimension);
		System.out.println("RAM: "+asus.ram);
		System.out.println("ROM: "+asus.rom);
	}
}

Output

 

Share Me!
  •  
  •  
  •  
  •  
  •  
  •