Java Notes – Classes
1. Introduction to Classes
A class in Java is a blueprint or template used to create objects. It represents a real-world entity
and defines its properties (variables) and behaviors (methods). Classes are the core building blocks
of object-oriented programming in Java.
Without classes, Java programs cannot model real-world problems effectively. Every Java
application consists of at least one class.
2. Syntax and Structure of a Class
The general syntax of a class includes an optional access modifier, the class keyword, the class
name, and the class body enclosed in curly braces.
Example syntax:
public class ClassName { variables; constructors; methods; }
Class names should follow PascalCase naming convention. A class may contain variables,
methods, constructors, blocks, and nested classes.
3. Components of a Class
Variables: Variables store data related to objects. They define the state of an object.
Types of variables in a class include instance variables (unique for each object) and static variables
(shared among all objects).
Methods: Methods define the behavior of a class. They perform actions and can return values.
Methods improve code reusability and readability. They are invoked using objects.
4. Constructors in a Class
A constructor is a special method used to initialize objects. It has the same name as the class and
does not have a return type.
Types of constructors include default constructors and parameterized constructors.
If no constructor is defined, Java provides a default constructor automatically.
Constructors are executed automatically when an object is created.
5. Object Creation and Usage of Classes
Objects are instances of a class. They are created using the new keyword.
Example: ClassName obj = new ClassName();
Multiple objects can be created from a single class. Each object has its own copy of instance
variables.
Classes and objects together help achieve abstraction, modularity, and reusability in Java
programs.