Articles

What is class?

What is class?

A class is the blueprint or template which defines the state or behavior that object of its type will support. 

 

In java, we cannot write any piece of code without using class. A class is the basic neccesity for writing a java code.

 

Given below is an example demonstrating the way java defines class:

public class Demo {
  //write your code here
}

class keywords indicates that we are creating a class.

Here 'Demo' is the name of the class. You may name it anything as per your wish.

 

Once you have declared your class, you can write:

  • methods,
  • create instances of other classes,
  • invoke other class,
  • print values and
  • do unlimited things.

 

To read in details about both the class and object go to our java tutorials class and object chapter

 

Lets see an example of complete java class with variables, methods, constructors, etc.

public class Employee {
	private String name; //variabe
	private String department; //variable
	private int empID; //variable
	private String grade; //variable
	
        //This is constructor
	public Employee(String name, String department, int empID){
		this.name = name;
		this.department = department;
		this.empID = empID;
	}
        //This is constructor	
	public Employee(String grade){
		this.grade = grade;
		getSalary(grade);
	}
	
        //This is a method to fetch salary of employee
	public void getSalary(String grade){
		if(grade.equals("A")){
			System.out.println("Grade A: 35000 INR");
		}else if(grade.equals("B")){
			System.out.println("Grade B: 25000 INR");
		}else{
			System.out.println("Default salary 15000 INR");
		}
	}
        
        //This is method to display the details of employee	
	public void displayEmployeeInfo(){
		System.out.println("Detail of the concerned Employee");
		System.out.println("Name:"+ " "+ name);
		System.out.println("Department:"+ " "+ department);
		System.out.println("Employee ID:"+ " "+ empID);
	}
}

This is how a well constructed class more or less looks like.

You can create your own class with more features as per requirement.


Java Interview Questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Rohanjit Kumar
Technology geek, loves to write and share knowledge with the world. Having 9+ years of IT experience. B.Tech in Computer Science & Engineering
Page Views :    Published Date : Jul 13,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!