Classes

A class is a blueprint for objects.

Example:

A typical Java class includes:

1. Instance Variables

These store data about the object.
Example: The person class has the instance variable “name”.

2. Methods

These define actions the object can perform.
Example: printName().

3. Constructors

Special methods used to create objects.

Example: Person p = new Person(“Bob”);

This line calls the constructor.

Key Features of Constructors:

  • They have the same name as the class.

  • They do NOT have a return type

  • They run once, at the moment the object is created.

  • You can have multiple constructors (this is called constructor overloading).

Default Constructor

If you don’t write any constructor, Java gives you one automatically:

public Person() { }

But as soon as you create your own constructor, the default one disappears unless you write it yourself.

Access Types:

public:

Accessible from anywhere in your program.

private:

Accessible only inside the same class.

protected:

Accessible in the same class and subclasses.