Understanding Class

Class is a blueprint/templete/prototype that describes some characteristics and behaviours(data and functions). The elements belonging to a class are said to be members of the class. Hence, the data values (fields) and functions(methods) described within the class are specifically called data members and member functions/methods respectively.Basically, a class lays the basis or foundation for creating various objects.

  • Need of a Class:
  • In Procedure oriented programming languages, the data items are left global to keep floating throughout the program. This technique causes problems in debugging logical errors. Hence, we need to have such a programming cencept in which data items should remain confined within the area of its application. This concept allows data items to remain hidden from the outside world and allows using only some essential features, called data hidding. It is an important concept of object oriented programming which can be implemented by using class.

  • Defining a Class:
  • A class can be defined by using the following syntax:

    public class
    {
    type_name instance_variable_1>
    type_name instance_variable_2>
    .
    .
    .
    type_name instance_variable_n>
    type_name method_name_1 (Parameter list)
    {
    //body of the method
    }
    type_name method_name_2(Parameter list)
    {
    //body of the method
    }
    .
    .
    .
    type_name method_name_n> {
    //body of the method
    }
    }
  • Example:
  • 1. Write a program with the following specifications: Class name : Rectangle Data members/Instant Variable : int length, int breadth Member functions : void inputdata(): to accept length and breadth of the rectangle void calculate() : to find area , perimeter and diagonal of the rectangle void outputdata(): to print the results.

    import java.util.*; class Rectangle { int l,b; int a,p; void inputdata() { Scanner sc=new Scanner(System.in); System.out.println("enter the length"); l=sc.nextInt(); System.out.println("enter the breadth"); b=sc.nextInt(); } void calculate() { a=l*b; p=2*(l+b); } void outputdata() { System.out.println("area=" +a); System.out.println("peri=" +p); } public static void main(String args[]) { Rectangle ob=new Rectangle(); ob.inputdata(); ob.calculate(); ob.outputdata(); } }

    OUTPUT:
    Enter the length:
    10
    Enter the breadth:
    4
    area=40
    peri=28

  • Conclusion:
  • In conclusion,Java classes serve as blueprints for objects, encapsulating data and behavior. They facilitate inheritance, polymorphism, and access control through modifiers. Constructors initialize objects, while static members are shared among instances. Abstraction is achieved via abstract classes and interfaces. Classes promote code organization, reusability, and modularity within packages, forming the foundation of scalable and maintainable Java applications.