Anatomy of a Class

Anatomy of a Class

Understanding Class Structure

  • A class in Java is a blueprint for creating objects.
  • It contains variables and methods that describe what the objects made from this class can do.

Key Components of a Class

  • The class name: This is the identifier that is used to create objects. The class name should be descriptive.
  • The class body: This is enclosed by braces {} and contains all the code that provides for the structure and behaviour of the objects formed from this class.

Class Declaration Format

  • The format typically is:
    public class ClassName {
      // variables
      // methods
    }
    
  • Here, public is an access modifier. Classes can also be declared as private or protected.

Instance Variables

  • Also known as fields, these are variables declared within a class, outside any method, and they are available to all methods in the class.
  • Each object will have its own set of instance variables.
  • They represent the properties of an object created from that class and can be of any data type (int, float, boolean, etc.).

Methods

  • Methods are basically a collection of statements that perform some operation.
  • They define the behaviour of objects of the class.
  • Methods can perform functions, return values, and use parameters to accept input.

Constructors

  • A constructor is a special type of method that is used to initialise objects.
  • The constructor is invoked when a new object is created.
  • The name of the constructor must be the same as the class name.
  • For example:
    public class ClassName {
      // constructor
      ClassName() {
          //initialise
      }
    }
    
  • Constructors can have parameters, and there can also be multiple constructors with different parameters (known as constructor overloading).

Importance of Class

  • A class is a basic unit of Encapsulation, one of the four principles of Object Oriented Programming (OOP).
  • With a class, it’s possible to encapsulate information and keep it from being altered or accessed unintentionally, promoting data security.
  • Understanding the anatomy of a class helps in the organised coding and designing of complex software applications, following the principles of OOP.