Defining Our Own Classes

Class Definition Syntax

class ClassName {
    // 1. Fields (instance variables)
    dataType fieldName;

    // 2. Constructor
    ClassName(parameters) {
        // initialization
    }

    // 3. Methods
    returnType methodName(parameters) {
        // code
        return value;
    }
}

Simple Class Example

class Book {
    // Fields
    String title;
    String author;
    double price;

    // Method to display details
    void display() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.println("Price: " + price);
    }
}

public class Main {
    public static void main(String[] args) {
        Book book = new Book();
        book.title = "Java Programming";
        book.author = "John Doe";
        book.price = 499.99;

        book.display();
    }
}

Class with Constructor

class Student {
    String name;
    int rollNo;
    double marks;

    // Constructor
    Student(String n, int r, double m) {
        name = n;
        rollNo = r;
        marks = m;
    }

    void display() {
        System.out.println("Name: " + name);
        System.out.println("Roll No: " + rollNo);
        System.out.println("Marks: " + marks);
    }

    String 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";
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("John", 101, 85.5);
        Student s2 = new Student("Alice", 102, 92.0);

        s1.display();
        System.out.println("Grade: " + s1.getGrade());

        s2.display();
        System.out.println("Grade: " + s2.getGrade());
    }
}

Class with Encapsulation

class Employee {
    // Private fields
    private String name;
    private int id;
    private double salary;

    // Constructor
    public Employee(String name, int id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }

    // Getters
    public String getName() {
        return name;
    }

    public int getId() {
        return id;
    }

    public double getSalary() {
        return salary;
    }

    // Setters
    public void setName(String name) {
        this.name = name;
    }

    public void setSalary(double salary) {
        if (salary > 0) {
            this.salary = salary;
        }
    }

    // Method to give raise
    public void giveRaise(double percentage) {
        salary = salary + (salary * percentage / 100);
    }

    public void display() {
        System.out.println("ID: " + id);
        System.out.println("Name: " + name);
        System.out.println("Salary: " + salary);
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee("John Doe", 1001, 50000);
        emp.display();

        emp.giveRaise(10);  // 10% raise
        System.out.println("\nAfter raise:");
        emp.display();
    }
}

Complete Class Example: Rectangle

class Rectangle {
    private double length;
    private double width;

    // Default constructor
    public Rectangle() {
        length = 1.0;
        width = 1.0;
    }

    // Parameterized constructor
    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Getters
    public double getLength() {
        return length;
    }

    public double getWidth() {
        return width;
    }

    // Setters with validation
    public void setLength(double length) {
        if (length > 0) {
            this.length = length;
        }
    }

    public void setWidth(double width) {
        if (width > 0) {
            this.width = width;
        }
    }

    // Calculate area
    public double getArea() {
        return length * width;
    }

    // Calculate perimeter
    public double getPerimeter() {
        return 2 * (length + width);
    }

    // Display details
    public void display() {
        System.out.println("Length: " + length);
        System.out.println("Width: " + width);
        System.out.println("Area: " + getArea());
        System.out.println("Perimeter: " + getPerimeter());
    }
}

public class Main {
    public static void main(String[] args) {
        Rectangle r1 = new Rectangle();  // Default
        Rectangle r2 = new Rectangle(5, 3);  // Custom

        System.out.println("Rectangle 1:");
        r1.display();

        System.out.println("\nRectangle 2:");
        r2.display();

        r2.setLength(10);
        System.out.println("\nAfter modification:");
        r2.display();
    }
}

Class Components

1. Fields (Instance Variables):

class Car {
    String brand;      // Field
    String model;      // Field
    int year;          // Field
}

2. Constructors:

class Car {
    String brand;

    // Constructor
    Car(String b) {
        brand = b;
    }
}

3. Methods:

class Car {
    String brand;

    void start() {     // Method
        System.out.println(brand + " started");
    }
}

Access Modifiers

class Example {
    public int publicField;       // Accessible everywhere
    private int privateField;     // Only within class
    protected int protectedField; // Within package and subclasses
    int defaultField;             // Within package (default)

    public void publicMethod() { }
    private void privateMethod() { }
    protected void protectedMethod() { }
    void defaultMethod() { }
}

this Keyword

Refers to current object.

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;  // this.name = field, name = parameter
        this.age = age;
    }

    void display() {
        System.out.println(this.name);  // Can use this
        System.out.println(age);        // Or omit if no conflict
    }
}

Best Practices

  1. Use meaningful names: Student, BankAccount
  2. Fields private: Encapsulation
  3. Methods public: Interface to outside
  4. Constructors: Initialize objects properly
  5. Getters/Setters: Controlled access
  6. Validation: Check values before setting
  7. this keyword: Distinguish fields from parameters

Quick Template

class ClassName {
    // Private fields
    private dataType field1;
    private dataType field2;

    // Constructor
    public ClassName(dataType field1, dataType field2) {
        this.field1 = field1;
        this.field2 = field2;
    }

    // Getters
    public dataType getField1() {
        return field1;
    }

    public dataType getField2() {
        return field2;
    }

    // Setters
    public void setField1(dataType field1) {
        this.field1 = field1;
    }

    public void setField2(dataType field2) {
        this.field2 = field2;
    }

    // Other methods
    public void display() {
        // Display logic
    }
}

Exam Tips

Remember:

  1. Class = Blueprint, Object = Instance
  2. Fields should be private
  3. Use constructors to initialize
  4. Provide getters/setters
  5. Use this for field-parameter conflict
  6. Methods define behavior
  7. Fields define properties
  8. Create objects with new

Common Questions:

  • How to define a class?
  • What are components of a class?
  • What is constructor?
  • Why make fields private?
  • What is this keyword?
  • How to create object?