Java is an object-oriented programming language, so everything in java program must be based on the object concept. In a java programming language, the class concept defines the skeleton of an object.
The java class is a template of an object. The class
defines the blueprint of an object. Every class in java forms a new data type.
Once a class got created, we can generate as many objects as we want. Every
class defines the properties and behaviors of an object. All the objects of a
class have the same properties and behaviors that were defined in the class.
Every class of java programming language has the
following characteristics.
- Identity - It is the name given to the class.
- State - Represents data values that are associated with an object.
- Behavior - Represents actions can be performed by an object.
In java, we use the keyword class to create a class. A class in java contains properties as variables and behaviors as methods. Following is the syntax of class in the java.
Syntax:
class <ClassName>{
data members
declaration;
methods
defination;
}
In java, an object is an instance of a class. When an object of a class is created, the class is said to be instantiated. All the objects that are created using a single class have the same properties and methods. But the value of properties is different for every object. Following is the syntax of class in the java.
Syntax
<ClassName> <objectName> = new <ClassName>(
);
Notes:
The objectName must begin with an alphabet, and a
Lower-case letter is preferred.
The objectName must follow all naming rules.
import java.util.Scanner;
class Employee {
// Data members (fields)
int empId;
String name;
double salary;
// Method to input employee details
void getDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Employee ID: ");
empId = sc.nextInt();
sc.nextLine(); // consume newline
System.out.print("Enter Employee Name: ");
name = sc.nextLine();
System.out.print("Enter Employee Salary: ");
salary = sc.nextDouble();
sc.close();
}
// Method to display employee details
void displayDetails() {
System.out.println("\nEmployee Details:");
System.out.println("ID: " + empId);
System.out.println("Name: " + name);
System.out.println("Salary: " + salary);
}
}
public class ArrayExample {
public static void main(String[] args) {
// Creating object of Employee class
Employee emp1 = new Employee();
// Calling methods using object
emp1.getDetails();
emp1.displayDetails();
}
}
Enter Employee ID: 11901
Enter Employee Name: Prasanjeet
Enter Employee Salary: 65000
Employee Details:
ID: 11901
Name: Prasanjeet
Salary: 65000.0