Java Basics

Classes and Objects

Learning Outcome

4

Use Non-Access Modifiers –

3

 Apply Access Modifiers

2

Use Constructors

1

Understand Classes and Objects

Variables: Know how to store data like int, double, String

Basic Java Syntax: Know how to write class, main method, and print output.

Before Starting ,Lets Recall

Methods (Functions): Understand how methods work, how to pass values and return results.

Arrays: Understand how methods work, how to pass values and return results

Think of a bakery where cakes are prepared every day

  • Before making a cake, the baker refers to a recipe book that explains how to prepare it.

 

  • Using the same recipe, the baker can make many cakes to serve customers.

 The bakery does not keep just one recipe.
It stores many related recipes together in one place so that they are easy to find and manage.

Once a cake is ready, it has specific characteristics, such as:Flavor,Size

A cake is not just something to look at.
Different actions can be performed on it:

  • The cake can be cut

  • The cake can be eaten

After the cake is completely eaten, the plate is no longer needed, so it is thrown away.

Similarly in java,

The recipe represents a class, as it defines how something should be created.

Each cake made using the recipe represents an object, as it is a real instance.

The flavor and size represent variables, as  they store the state of the cake.

Actions like cutting and eating represent methods, as they define behavior.

Clearing the plate after the cake is finished represents garbage collection, as unused items are removed automatically.

The initial decisions made while baking represent a constructor, as it initializes the cake.

The bakery that stores many recipes together represents a package, as it organizes related classes.

What is Class and Object in Java?

Object: The Real Thing

An object is a real instance created from a class. It uses the class blueprint to store actual data and perform specific actions.

Real Example: ChocolateCake and VanillaCake are objects created from the CakeRecipe class.

Class: The Blueprint

Bakery Analogy: A cake recipe is like a class—it defines ingredients and baking steps but isn't the actual cake itself.

A class is a template that defines what an object will contain (variables) and what actions it can perform (methods).

Java Syntax for Classes and Objects

Class Syntax

class ClassName {
    // Fields (variables)
    // Methods (functions)
}
ClassName variable = 
    new ClassName();

Object Creation

Complete Working Example

class Cake {
    String flavor;

    void bake() {
        System.out.println("Baking " + flavor + " cake");
    }
}

 

 

public class Main {
    public static void main(String[] args) {
        Cake c1 = new Cake();
        c1.flavor = "Chocolate";
        c1.bake();
    }
}

Constructors in Java

A constructor is a special method used to initialize objects. It runs automatically when an object is created.

Key Rules

No return type, not even void.

Name must be the same as the class name.

Executed automatically upon using the new keyword.

class ClassName {

    // Constructor
    ClassName() {
        // initialization code
    }
}

Syntax

class Student {

    String name;
    int age;

    // Constructor
    Student(String n, int a) {
        name = n;
        age = a;
    }
}

public class Main {
    public static void main(String[] args) {

        Student s1 = new Student("Rahul", 20);
    }
}

Example:

Types of Constructor

Default Constructor

  • Provided automatically by the compiler

  • Sets default values

class Student {
  // Compiler adds: Student() {}
}

No-Argument Constructor

  • Written by the programmer

  • Used for custom initialization

class Student {
  Student() {
    System.out.println("Object created");

}}

Parameterized Constructor

  • Accepts arguments for initialization

  • Avoids extra setter calls

class Student {
Student(String name) {

 System.out.println("Name:"+ name);
 }}

Copy Constructor

  • Creates a new object using another object’s data

  • Must be defined manually

class Student {

    Student(Student s) {
        System.out.println("Object copied");
    }}

Destructors in Java

A destructor is a special method used to clean up resources before an object is destroyed.

No Explicit Destructor

Unlike C++, Java does not use manual destructors.

Java uses Garbage Collection (GC) to automatically remove unused objects.

The finalize() method exists for cleanup but is deprecated and rarely used.

class Cake {

    protected void finalize() {

        System.out.println("Object is destroyed");

    }

}

Example:

Access Modifiers in Java

Access modifiers control who can see or use variables and methods in a class.

Private

  • Accessible only within the classitself.

public

  • Accessible from anywhere. No restrictions.

Protected

  • Same package + subclasses.

Default

  • No keyword. Accessible only in same package.

Non-Access Modifiers in Java

Non-access modifiers change the behavior of variables, methods, or classes.

Static

  • Belongs to Class, shared by all objects.

Final

  • Cannot be changed once assigned.

Encapsulation

Encapsulation means wrapping data and methods together and protecting the data from outside misuse.

 It is done by:

  • making variables private
     

  • giving access through public methods (getters & setters)

Why Encapsulation is needed

Protects data from wrong changes

Controls how data is accessed

Makes code safe and clean

POJO Class in Encapsulation

A POJO (Plain Old Java Object) is a simple Java class that is used to store data and follows the concept of encapsulation.

Why POJO Is Used in Encapsulation?

In a POJO, variables are marked private.

POJO uses public getters and setters to access data.

  • Used to read/get the value of a private variable
     

  • Starts with get

Getter Method

  • Used to set/update the value of a private variable
     

  • Starts with set

Setter Method

Getter and Setter Methods

class Student{
private int age;
public int getAge(){return age;}
public void setAge(int age){this.age=age;}
}

 

public class Main{
public static void main(String[] args){
Student s=new Student();
s.setAge(20);
System.out.println(s.getAge());
}
}

Example:

Dynamic Memory Allocation & Garbage Collection in Java

2. Garbage Collection

  •  Java automatically deletes objects no longer used.
  • Bakery analogy: Old cake plates are cleaned automatically.

1. Dynamic Memory Allocation

  • Memory for objects is created when needed using new.
  • Bakery analogy: Make a cake only when an order comes.

What is Package in java

  •  A package is a way to organize classes in Java, like putting them into folders.
  • It helps keep code organized and avoid name conflicts.

bakery(Package)

Cakes

ChocolateCake.java

breads

package com.school;

public class Student{
public void show(){
System.out.println("Student class inside package");
}
 

package com.school;

public class Main{
public static void main(String[] args){
Student s=new Student();
s.show();
}
 

Main.java

Student.java

Example:

Inbuilt  Package in java

 java.lang → Basic classes (String, Math, Object)

java.util → Utilities & data structures (ArrayList, Scanner)

 java.io → Input/output (File, BufferedReader)

 java.sql → Database access (Connection, ResultSet)

java.net → Networking (URL, Socket)

Summary

5

Packages organize classes efficiently.

4

Encapsulation hides data safely.

3

Modifiers control visibility and behavior.

2

Constructor initializes objects, garbage collector cleans.

1

Class defines structure, object represents instance.

Quiz

How do you create an object in Java?

A. ClassName obj;

B. ClassName obj = new ClassName();

C. new ClassName;

D. obj = ClassName();

How do you create an object in Java?

A. ClassName obj;

B. ClassName obj = new ClassName();

C. new ClassName;

D. obj = ClassName();

Quiz-Answer