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>
Where,
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
Example
public class Fruit{
String name; // field
String color; // field
void vitamin(){ // method
}
void taste(){ // method
}
}
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
Syntax
Keyword new is used to create object of class.
<Class_Name> Object_Name = new <Class_Name>();
Example
Fruit f = new Fruit ();
To access the method of class use the following syntax:
f.taste();
Example
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 ();
add.total(10, 20);
}
}
Output
Addition of two numbers: 30