Skip to main content
Classes and Objects
  1. Resources/
  2. Study Materials/
  3. Information & Communication Technology Engineering/
  4. ICT Semester 4/
  5. Java Programming (4343203)/
  6. Java Programming Slidev Presentations/

Classes and Objects

·
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

Classes and Objects
#

Lecture 11
#

Java Programming (4343203)
Diploma in ICT - Semester IV
Gujarat Technological University

Press Space for next page

layout: default
#

Learning Objectives
#

By the end of this lecture, you will be able to:

  • ๐Ÿ—๏ธ Define classes with proper syntax and structure
  • ๐ŸŽฏ Create objects and understand object instantiation
  • ๐Ÿ“Š Implement instance variables (fields) effectively
  • ๐Ÿ”ง Write methods to define object behavior
  • ๐Ÿญ Practice with required syllabus exercises
  • ๐Ÿ’ก Apply OOP principles in real programming scenarios

Let's build our first Java classes! ๐Ÿ—๏ธ๐ŸŽฏ

layout: center
#

Class and Object Relationship
#

graph TD
    A[Class: Student] --> B[Object: student1<br/>Name: Alice<br/>RollNo: 101<br/>Marks: 85]
    A --> C[Object: student2<br/>Name: Bob<br/>RollNo: 102<br/>Marks: 92]
    A --> D[Object: student3<br/>Name: Charlie<br/>RollNo: 103<br/>Marks: 78]
    
    E[Class is a Blueprint] --> F[Objects are Instances]
    
    style A fill:#e3f2fd
    style B fill:#e8f5e8
    style C fill:#e8f5e8
    style D fill:#e8f5e8
    style E fill:#fff3e0
    style F fill:#f3e5f5

๐Ÿ“‹ Class

  • โ€ข Template or blueprint
  • โ€ข Defines structure and behavior
  • โ€ข No memory allocation
  • โ€ข Written once, used many times

๐ŸŽฏ Object

  • โ€ข Instance of a class
  • โ€ข Has actual data values
  • โ€ข Memory allocated
  • โ€ข Each object is unique

layout: default
#

Defining a Class
#

๐Ÿ—๏ธ Class Syntax Structure
#

[access_modifier] class ClassName {
    // Instance variables (fields)
    data_type variable1;
    data_type variable2;
    
    // Constructor(s)
    public ClassName() {
        // initialization code
    }
    
    // Methods
    return_type methodName() {
        // method body
    }
}

๐Ÿ“‹ Class Components
#

  • Class Declaration: class ClassName
  • Instance Variables: Store object state
  • Methods: Define object behavior
  • Constructors: Initialize objects

๐Ÿ“ Simple Class Example
#

// Student.java
public class Student {
    // Instance variables (attributes)
    String enrollmentNo;
    String name;
    int age;
    String branch;
    double marks;
    
    // Method to display student details
    public void displayInfo() {
        System.out.println("=== Student Information ===");
        System.out.println("Enrollment No: " + enrollmentNo);
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Branch: " + branch);
        System.out.println("Marks: " + marks);
    }
    
    // Method to calculate grade
    public char getGrade() {
        if (marks >= 90) return 'A';
        else if (marks >= 80) return 'B';
        else if (marks >= 70) return 'C';
        else if (marks >= 60) return 'D';
        else return 'F';
    }
    
    // Method to check if passed
    public boolean hasPassed() {
        return marks >= 40;
    }
}

layout: default
#

Creating Objects
#

๐ŸŽฏ Object Creation Syntax
#

// Syntax: ClassName objectName = new ClassName();

// Step 1: Declaration
Student student1;

// Step 2: Instantiation
student1 = new Student();

// Combined (most common)
Student student2 = new Student();

// Multiple objects
Student alice = new Student();
Student bob = new Student();
Student charlie = new Student();

๐Ÿ” Memory Allocation
#

  • Declaration: Creates reference variable
  • new keyword: Allocates memory in heap
  • Constructor call: Initializes the object
  • Reference assignment: Points to object

๐Ÿ“ Syllabus Exercise: Student Class
#

// Required: Create Student class with enrollmentNo and name
public class StudentDemo {
    public static void main(String[] args) {
        // Create 3 objects of Student class
        Student student1 = new Student();
        Student student2 = new Student();
        Student student3 = new Student();
        
        // Set data for student1
        student1.enrollmentNo = "21ICT001";
        student1.name = "Alice Johnson";
        student1.age = 19;
        student1.branch = "ICT";
        student1.marks = 87.5;
        
        // Set data for student2
        student2.enrollmentNo = "21ICT002";
        student2.name = "Bob Smith";
        student2.age = 20;
        student2.branch = "ICT";
        student2.marks = 92.3;
        
        // Set data for student3
        student3.enrollmentNo = "21ICT003";
        student3.name = "Charlie Brown";
        student3.age = 19;
        student3.branch = "ICT";
        student3.marks = 76.8;
        
        // Display student names (as required)
        System.out.println("Student Names:");
        System.out.println("1. " + student1.name);
        System.out.println("2. " + student2.name);
        System.out.println("3. " + student3.name);
        
        // Display complete information
        System.out.println("\n" + "=".repeat(40));
        student1.displayInfo();
        System.out.println("Grade: " + student1.getGrade());
        System.out.println("Passed: " + student1.hasPassed());
    }
}

layout: default
#

Instance Variables (Fields)
#

๐Ÿ“Š Understanding Instance Variables
#

  • Store object state/data
  • Each object has its own copy
  • Initialized with default values
  • Accessible throughout the class
  • Define object properties

๐Ÿ” Default Values
#

Data TypeDefault Value
int0
double0.0
booleanfalse
Stringnull
char‘\u0000’

๐Ÿ“ Instance Variables Example
#

public class Rectangle {
    // Instance variables
    int length;     // Default: 0
    int width;      // Default: 0
    String color;   // Default: null
    boolean filled; // Default: false
    
    // Method to set dimensions
    public void setDimensions(int l, int w) {
        length = l;
        width = w;
    }
    
    // Method to calculate area
    public int calculateArea() {
        return length * width;
    }
    
    // Method to calculate perimeter
    public int calculatePerimeter() {
        return 2 * (length + width);
    }
    
    // Method to display rectangle info
    public void displayInfo() {
        System.out.println("Rectangle Details:");
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
        System.out.println("Color: " + color);
        System.out.println("Filled: " + filled);
        System.out.println("Area: " + calculateArea());
        System.out.println("Perimeter: " + calculatePerimeter());
    }
}

layout: default
#

Methods in Classes
#

๐Ÿ”ง Method Structure
#

[access_modifier] return_type methodName(parameters) {
    // method body
    // return statement (if needed)
}

๐Ÿ“‹ Method Types
#

By Return Type:

  • void methods: No return value
  • value-returning methods: Return a value

By Parameters:

  • No parameters: displayInfo()
  • With parameters: setMarks(double marks)

By Purpose:

  • Accessor methods: Get data (getters)
  • Mutator methods: Set data (setters)
  • Utility methods: Perform calculations

๐Ÿ“ Method Examples
#

public class BankAccount {
    String accountNumber;
    String holderName;
    double balance;
    
    // Setter method (mutator)
    public void setBalance(double amount) {
        if (amount >= 0) {
            balance = amount;
        } else {
            System.out.println("Invalid amount");
        }
    }
    
    // Getter method (accessor)
    public double getBalance() {
        return balance;
    }
    
    // Utility method with parameters
    public boolean withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            return true;
        }
        return false;
    }
    
    // Utility method with return value
    public double calculateInterest(double rate) {
        return balance * rate / 100;
    }
    
    // void method for display
    public void displayAccountInfo() {
        System.out.println("Account: " + accountNumber);
        System.out.println("Holder: " + holderName);
        System.out.println("Balance: โ‚น" + balance);
    }
}

layout: default
#

Syllabus Exercise: Rectangle Class
#

๐Ÿ—๏ธ Required Implementation
#

// Rectangle.java - Syllabus requirement
public class Rectangle {
    // Instance variables for height and width
    int height;
    int width;
    
    // Method to set dimensions
    public void setDimensions(int h, int w) {
        height = h;
        width = w;
        System.out.println("Rectangle dimensions set:");
        System.out.println("Height: " + height);
        System.out.println("Width: " + width);
    }
    
    // Method to calculate area
    public int calculateArea() {
        return height * width;
    }
    
    // Method to calculate perimeter
    public int calculatePerimeter() {
        return 2 * (height + width);
    }
    
    // Method to check if it's a square
    public boolean isSquare() {
        return height == width;
    }
    
    // Method to display complete info
    public void displayInfo() {
        System.out.println("\n=== Rectangle Information ===");
        System.out.println("Height: " + height + " units");
        System.out.println("Width: " + width + " units");
        System.out.println("Area: " + calculateArea() + " sq units");
        System.out.println("Perimeter: " + calculatePerimeter() + " units");
        System.out.println("Is Square: " + isSquare());
    }
}
// Main.java - Testing the Rectangle class
public class RectangleDemo {
    public static void main(String[] args) {
        // Create Rectangle objects
        Rectangle rect1 = new Rectangle();
        Rectangle rect2 = new Rectangle();
        Rectangle rect3 = new Rectangle();
        
        // Set dimensions for rectangles
        System.out.println("Creating Rectangle 1:");
        rect1.setDimensions(5, 10);
        
        System.out.println("\nCreating Rectangle 2:");
        rect2.setDimensions(7, 7);
        
        System.out.println("\nCreating Rectangle 3:");
        rect3.setDimensions(8, 12);
        
        // Display information for all rectangles
        rect1.displayInfo();
        rect2.displayInfo();
        rect3.displayInfo();
        
        // Compare areas
        System.out.println("\n=== Area Comparison ===");
        int area1 = rect1.calculateArea();
        int area2 = rect2.calculateArea();
        int area3 = rect3.calculateArea();
        
        System.out.println("Rectangle 1 area: " + area1);
        System.out.println("Rectangle 2 area: " + area2);
        System.out.println("Rectangle 3 area: " + area3);
        
        // Find largest rectangle
        if (area1 >= area2 && area1 >= area3) {
            System.out.println("Rectangle 1 has the largest area");
        } else if (area2 >= area1 && area2 >= area3) {
            System.out.println("Rectangle 2 has the largest area");
        } else {
            System.out.println("Rectangle 3 has the largest area");
        }
    }
}

layout: default
#

Object Interaction and Communication
#

๐Ÿ”— Objects Working Together
#

// Course.java
public class Course {
    String courseCode;
    String courseName;
    int credits;
    
    public void setCourseInfo(String code, String name, int cr) {
        courseCode = code;
        courseName = name;
        credits = cr;
    }
    
    public void displayCourse() {
        System.out.println(courseCode + ": " + courseName + 
                         " (" + credits + " credits)");
    }
}

// Student.java (enhanced)
public class Student {
    String name;
    String rollNumber;
    Course[] enrolledCourses;
    int courseCount;
    
    public Student() {
        enrolledCourses = new Course[5]; // Max 5 courses
        courseCount = 0;
    }
    
    public void enrollInCourse(Course course) {
        if (courseCount < 5) {
            enrolledCourses[courseCount] = course;
            courseCount++;
            System.out.println(name + " enrolled in course: " + 
                             course.courseName);
        }
    }
    
    public void displayEnrolledCourses() {
        System.out.println(name + "'s enrolled courses:");
        for (int i = 0; i < courseCount; i++) {
            enrolledCourses[i].displayCourse();
        }
    }
}

๐Ÿ“ Using Object Interaction
#

public class UniversityDemo {
    public static void main(String[] args) {
        // Create student object
        Student student = new Student();
        student.name = "Alice Johnson";
        student.rollNumber = "21ICT001";
        
        // Create course objects
        Course course1 = new Course();
        course1.setCourseInfo("ICT101", "Programming Fundamentals", 4);
        
        Course course2 = new Course();
        course2.setCourseInfo("ICT102", "Database Systems", 3);
        
        Course course3 = new Course();
        course3.setCourseInfo("ICT103", "Web Development", 3);
        
        // Student enrolls in courses
        student.enrollInCourse(course1);
        student.enrollInCourse(course2);
        student.enrollInCourse(course3);
        
        // Display student's courses
        System.out.println("\n" + "=".repeat(40));
        student.displayEnrolledCourses();
        
        // Calculate total credits
        int totalCredits = 0;
        for (int i = 0; i < student.courseCount; i++) {
            totalCredits += student.enrolledCourses[i].credits;
        }
        System.out.println("Total Credits: " + totalCredits);
    }
}
๐ŸŽฏ Key Concept: Objects can contain and interact with other objects!

layout: default
#

Real-World Class Design
#

๐Ÿญ Complete Class Example: Library Management
#

// Book.java
public class Book {
    String isbn;
    String title;
    String author;
    String publisher;
    int totalCopies;
    int availableCopies;
    double price;
    
    // Initialize book data
    public void setBookInfo(String isbn, String title, 
                           String author, int copies, double price) {
        this.isbn = isbn;
        this.title = title;
        this.author = author;
        this.totalCopies = copies;
        this.availableCopies = copies;
        this.price = price;
    }
    
    // Issue a book
    public boolean issueBook() {
        if (availableCopies > 0) {
            availableCopies--;
            System.out.println("Book issued successfully");
            return true;
        } else {
            System.out.println("Book not available");
            return false;
        }
    }
    
    // Return a book
    public void returnBook() {
        if (availableCopies < totalCopies) {
            availableCopies++;
            System.out.println("Book returned successfully");
        } else {
            System.out.println("All copies already returned");
        }
    }
    
    // Check availability
    public boolean isAvailable() {
        return availableCopies > 0;
    }
}
// Member.java
public class Member {
    String memberId;
    String name;
    String email;
    String phone;
    int booksIssued;
    int maxBooks;
    
    public Member() {
        booksIssued = 0;
        maxBooks = 3; // Default limit
    }
    
    public void setMemberInfo(String id, String name, 
                             String email, String phone) {
        this.memberId = id;
        this.name = name;
        this.email = email;
        this.phone = phone;
    }
    
    public boolean canIssueBook() {
        return booksIssued < maxBooks;
    }
    
    public void issueBookToMember() {
        if (canIssueBook()) {
            booksIssued++;
            System.out.println("Book issued to " + name);
        } else {
            System.out.println("Maximum book limit reached");
        }
    }
    
    public void returnBookFromMember() {
        if (booksIssued > 0) {
            booksIssued--;
            System.out.println("Book returned by " + name);
        }
    }
    
    public void displayMemberInfo() {
        System.out.println("Member ID: " + memberId);
        System.out.println("Name: " + name);
        System.out.println("Books Issued: " + booksIssued + "/" + maxBooks);
    }
}

layout: default
#

Class Design Best Practices
#

โœ… Good Practices
#

Naming Conventions:

  • Class names: PascalCase (StudentRecord)
  • Variable names: camelCase (firstName)
  • Method names: camelCase (calculateGrade)
  • Constants: UPPER_CASE (MAX_STUDENTS)

Class Organization:

  • Instance variables first
  • Constructors next
  • Methods last
  • Group related methods together

Method Design:

  • Single responsibility per method
  • Meaningful method names
  • Appropriate return types
  • Proper parameter validation

๐ŸŽฏ Design Principles
#

Keep It Simple:

  • One class, one responsibility
  • Avoid overly complex classes
  • Clear and intuitive interfaces

Data Protection:

  • Use appropriate access modifiers
  • Validate input parameters
  • Provide safe access methods

Maintainability:

  • Add meaningful comments
  • Use descriptive variable names
  • Follow consistent formatting

Reusability:

  • Design for reuse
  • Avoid hard-coded values
  • Make classes flexible
๐ŸŒŸ Remember: Good class design leads to maintainable and reusable code!

layout: default
#

Hands-On Programming Exercise
#

๐Ÿ› ๏ธ Build a Complete Class System
#

Task 1: Create a Student class with enrollmentNo and name, instantiate 3 objects (Syllabus requirement)
Task 2: Create a Rectangle class with height and width, initialize via constructor (Syllabus requirement)
Task 3: Design a BankAccount class with account number, holder name, and balance with appropriate methods
Task 4: Create a Product class for an inventory system with proper object interactions
Task 5: Implement a Employee class with salary calculation and bonus methods

๐ŸŽฏ Success Criteria
#

  • Proper class structure and naming
  • Appropriate instance variables
  • Well-designed methods
  • Object creation and manipulation
  • Real-world applicability

layout: default
#

Common Mistakes and Solutions
#

โŒ Common Mistakes
#

Class Design Issues:

// Too many responsibilities
class StudentTeacherCourse {
    // Managing students, teachers, and courses
    // Violates single responsibility
}

Variable Access:

Student s = new Student();
System.out.println(s.name); // Accessing uninitialized field

Method Naming:

public void abc() { } // Meaningless name
public int xyz(int a, int b) { } // Unclear purpose

Memory Issues:

Student s1 = new Student();
Student s2 = s1; // Both reference same object
s2.name = "John"; // Changes s1.name too

โœ… Solutions
#

Single Responsibility:

class Student { /* Only student-related data/methods */ }
class Teacher { /* Only teacher-related data/methods */ }
class Course  { /* Only course-related data/methods */ }

Proper Initialization:

Student s = new Student();
s.name = "Alice";
s.enrollmentNo = "21ICT001";
System.out.println(s.name); // Safe access

Meaningful Names:

public void displayStudentInfo() { }
public double calculateGPA(int[] marks) { }

Independent Objects:

Student s1 = new Student();
Student s2 = new Student(); // Separate objects
s1.name = "Alice";
s2.name = "Bob"; // Independent data

layout: default
#

Memory Model: Classes vs Objects
#

graph TD
    A[Class: Student<br/>Code Area] --> B[Method Area<br/>Class Definition]
    
    C[Object: student1<br/>Heap Memory] --> D[name: Alice<br/>rollNo: 101<br/>marks: 85]
    C --> E[Reference to Methods]
    
    F[Object: student2<br/>Heap Memory] --> G[name: Bob<br/>rollNo: 102<br/>marks: 92]
    F --> H[Reference to Methods]
    
    I[Stack Memory] --> J[student1 reference]
    I --> K[student2 reference]
    
    J --> C
    K --> F
    E --> B
    H --> B
    
    style A fill:#e3f2fd
    style C fill:#e8f5e8
    style F fill:#e8f5e8
    style I fill:#fff3e0
    style B fill:#f3e5f5

๐Ÿ“‹ Method Area

Class definitions stored

๐Ÿ—๏ธ Heap Memory

Objects allocated here

๐Ÿ“š Stack Memory

References stored here


layout: center class: text-center
#

Summary
#

๐Ÿ“– What We Learned

  • โ€ข Class definition syntax and structure
  • โ€ข Object creation and instantiation
  • โ€ข Instance variables and their usage
  • โ€ข Method implementation and types
  • โ€ข Required syllabus exercises
  • โ€ข Object interaction and communication

๐ŸŽฏ Next Steps

  • โ€ข Access modifiers (public, private, protected)
  • โ€ข Data encapsulation and hiding
  • โ€ข Getter and setter methods
  • โ€ข Security and access control
  • โ€ข Professional class design
Classes and objects mastered! ๐Ÿ—๏ธ๐ŸŽฏ

layout: center class: text-center
#

Questions & Discussion
#

โ“
Any questions about classes, objects, instance variables, or methods?
Next lecture: **Access Modifiers and Data Protection**
Ready to secure your classes! ๐Ÿ‘