Classes and Objects in Java

Classes in Java

It is basically a collection of objects. It is a template which creates objects that defines its state and behavior. A class contains field and method to define the state and behavior of its object.
Syntax for Declaring Class:

<Access_Modifier> class <Class_Name>

Class_Name: It describes the class name which defines by using class keyword.
Access_Modifier : It defines the scope of the data member, method or class i.e.  who can access class and members of the class. There are three access modifiers in java:

  • Public – Accessible everywhere
  • Default – Accessible only within the package. If you not using any modifier then default is considered
  • Private – Accessible only within the class
  • Protected – Accessible within package and outside the package but during inheritance only 


public class Fruit{
String name;  // field
String color;  // field
void vitamin(){  // method
void taste(){  // method

Learn Java

Learn how to use the Super Keyword in Java to access the methods and variables of the parent class!

Objects in Java

An object is an instance of a class. Class and Objects has state and behavior. For example a fruit has states – name, color and behaviors – vitamin, taste
Keyword new is used to create object of class.

<Class_Name>   Object_Name = new <Class_Name>();


Fruit f = new Fruit ();

Learn Java from scratch with this free Java Tutorial!

To access the method of class use the following syntax:



public class Addition{
int sum;
public void total(int a, int b){
sum = a + b;
System.out.println("Addition of two numbers:" +sum );
public static void main(String []args){
Addition add = new Addition ();, 20);

Addition of two numbers: 30

Explore these top Java Collection Interview Questions and ace your next interview to get your dream job!

Course Schedule

Name Date Details
Python Course 02 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 09 Mar 2024(Sat-Sun) Weekend Batch
View Details
Python Course 16 Mar 2024(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *