Object Oriented Programming with Java

⌘K
  1. Home
  2. Docs
  3. Object Oriented Programmi...
  4. Classes and Objects
  5. Defining Classes in Java

Defining Classes in Java

A class is a blueprint for creating objects. It defines the properties (attributes) and behaviors (methods) of objects.

Defining Classes in Java includes these components:

  • Adding Instance Variables
  • Adding Instance Methods
  • Adding Variables
  • Adding Methods
  • Adding Static Methods

These are non-static variables defined inside a class but outside any method. Each object gets its own copy.

class Student {
    String name;
    int age;
}

Instance methods operate on instance variables.

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }

    void display() {
        System.out.println("Student Name: " + name);
    }

    public static void main(String[] args) {
        Student s = new Student("John");
        s.display();  // Output: Student Name: John
    }
}

Class variables are shared among all instances. Declared with static.

class Employee {
    static String company = "Tech Corp";  // Class variable

    String name;

    Employee(String name) {
        this.name = name;
    }

    public static void main(String[] args) {
        Employee e1 = new Employee("Alice");
        Employee e2 = new Employee("Bob");

        System.out.println(e1.company);  // Output: Tech Corp
        System.out.println(e2.company);  // Output: Tech Corp
    }
}

Static methods work with class variables or logic that doesn’t depend on instance state.

class Employee {
    static String company = "Tech Corp";

    static void changeCompany(String newCompany) {
        company = newCompany;
    }

    public static void main(String[] args) {
        Employee.changeCompany("NewTech");
        System.out.println(Employee.company);  // Output: NewTech
    }
}

Static methods are utility methods and do not depend on object state.

class MathOperations {
    static int add(int a, int b) {
        return a + b;
    }

    public static void main(String[] args) {
        System.out.println(MathOperations.add(5, 3));  // Output: 8
    }
}

How can we help?

Discussion 0

Join the Conversation

Your email address will not be published. Required fields are marked *