Hi guys in this article let’s learn about class.You might be thinking that you use class in every single program but don’t know what is class so let’s start.Hope you’ll enjoy it 🙂
Class is the core of Java.Each every single thing in java is referred as object and class. To understand the concept of classes and objects let’s take a real world examples and understand in a better way.
For eg: If there are many examples of trees such as mango tree,neem tree,Papaya tree etc. We refer these the examples of trees as objects and the tree as class.So why did we refer tree…?? Because they all have the features in common that’s why they belong under the same class called tree and the names of trees are called objects.
Now moving to technical definition, Classes contain set of functions which are defined completely and if we declare objects of the class it contains all the access towards the functions.So the class start with the keyword class followed by classname. In Java the main function is also declared inside the class. We can declare the functions of the class outside by defining the object of that required class and accessing the functions with those objects.And the variables in class are given with access specifier this defines how the variables can be accessed.There are four access specifier private,default,protected and public.You’ll be learning about these access specifier in my future posts for just understand that these define the scope of the variables.
The variables declared with private can be acessed only inside the same class and cannot be accessed outside,protected variables can be accessed within the class and sub-classes,default variables can be accessed within the package and public variables can be accessed anywhere.
Syntax: class classname
{
datatype variablename1,2…..n;
datatype methodname(arguments)
{
\Definition of this method
}
}
Let’s see simple example of class
Code goes here:
import java.util.*;
class student
{
private int rollno; //as this variable is declared as private it can be accessed only inside this class not outside the class
private String name;
public void readStudent()//declaring the required functions inside the class
{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the rollno and name of the student");
rollno=scan.nextInt();
name=scan.next();
}
public void displaystudent()
{
System.out.println("Roll number:"+rollno+" "+"Name:"+name);
}
}
class Main
{
public static void main(String args[])
{
student s; //declaring the objects of class
s=new student(); //creating the instance of class
s.readStudent();//acessing the methos by objects
s.displaystudent();
}
}