Java Object-Oriented Programming: Class, Object, Attributes & Methods

package my_proj;

public class my_first {
    int i = 20;  // Attribute (instance variable) of class my_first

    public static void main(String[] args) {
        my_first my_num = new my_first();  // Object created
        System.out.println(my_num.i);      // Accessed via dot (.) notation -> 20
    }
}

Output:

20

1. Identifying Class, Object, Attribute & Method 🔝

OOP Term Syntax in Code Role in Java
Class class my_first { ... } The blueprint or template that defines attributes and methods.
Object new my_first() A runtime instance of a class allocated on the heap (e.g., my_num, obj1).
Attribute (Field) int i = 20; A variable declared inside a class, accessed via dot notation (my_num.i).
Method void adder() { ... } A reusable function attached to a class that performs a task or calculation.

2. Creating Methods, Updating Attributes & the final Keyword 🔝

In the example below, obj1.j = 40; updates the attribute j before calling obj1.adder(). If you want to lock an attribute so it can never be reassigned, declare it with the final keyword (final int j = 10;):

package Pack1;

class my_first {
    int i = 20;
    int j = 10;
     // Note: If declared as 'final int j = 10;', reassigning obj1.j = 40 causes:
     // Compile Error: The final field my_first.j cannot be assigned

    public void adder() {
        System.out.println(i + j);
    }

    public static void main(String[] args) {
        my_first obj1 = new my_first();
        System.out.println(obj1.i);  // 20
        obj1.j = 40;                 // Updates attribute j from 10 to 40
        obj1.adder();                // 20 + 40 = 60
    }
}

Terminal Output:

20
60

3. Calling Methods Across Two Separate Classes (my_first & my_second) 🔝

You can define reusable arithmetic methods (adder(), my_subtract(), my_multiply(), my_devide()) inside my_first and instantiate my_first inside a second class my_second in the same package:

package Pack1;

class my_first {
    int i = 20;
    int j;
    public void adder()       { System.out.println(i + j); }
    public void my_subtract() { System.out.println(i - j); }
    public void my_multiply() { System.out.println(i * j); }
    public void my_devide()   { System.out.println(i / j); }
}

public class my_second {
    public static void main(String[] args) {
        my_first obj2 = new my_first();
        obj2.j = 20;
        obj2.i = 40;
        obj2.adder();
        obj2.my_subtract();
        obj2.my_multiply();
        obj2.my_devide();
    }
}

Terminal Output:

60
20
800
2

4. Access Control: public vs private Methods 🔝

If you change public void my_subtract() in my_first to private void my_subtract(), calling obj2.my_subtract() from my_second fails at compile time with The method my_subtract() from the type my_first is not visible:

Access Modifier Same Class Same Package All Classes Everywhere
public Yes Yes Yes
protected Yes Yes Subclasses only
Default (no modifier) Yes Yes No
private Yes (Only) No No

5. Difference Between static Methods and Instance (public) Methods 🔝

A static method (like my_static()) belongs to the class itself and can be invoked directly without creating an object. A non-static method (like my_public()) requires an object instance (obj1.my_public()):

package Pack1;

public class my_second {
    static void my_static() {
        System.out.println("Hi this is my_static");
    }
    public void my_public() {
        System.out.println("Hi this is my_public");
    }
    public static void main(String[] args) {
         // Instance method requires an object instance:
        my_second obj1 = new my_second();
        obj1.my_public();

         // Static method can be called directly without an object:
        my_static();
    }
}

Terminal Output:

Hi this is my_public
Hi this is my_static

6. Passing Parameters & Returning a Value from a Method 🔝

Java Class, Object and Method Parameter Passing

Instead of hardcoding values inside attributes, you can pass arguments (12, 13) into myObj.adding(int x, int y) and capture the returned int sum:

class my_add {
    int adding(int x, int y) {
        return x + y;
    }
}

public class my_test_class {
    public static void main(String[] args) {
        my_add myObj = new my_add();
        int z = myObj.adding(12, 13);
        System.out.println(z);
    }
}

Terminal Output:

25

7. Initializing Objects Cleanly with a Constructor 🔝

A constructor is a special method whose name matches the class name and has no return type. It runs automatically when new is called:

public class StudentRecord {
    String name;
    int score;

     // Parameterized constructor initializes attributes at object creation time:
    public StudentRecord(String name, int score) {
        this.name = name;
        this.score = score;
    }
    public static void main(String[] args) {
        StudentRecord s1 = new StudentRecord("Rama", 92);
        System.out.println(s1.name + " scored " + s1.score);
    }
}

Terminal Output:

Rama scored 92

8. Practical Recipe: Encapsulation with private Fields & Getters 🔝

In production Java code, attributes are declared private and read or updated through validated public methods so invalid state (like negative deposits) is rejected:

public class BankAccount {
    private int balance = 1000;  // Private field hidden from outside classes

    public int getBalance() { return balance; }
    public void deposit(int amount) {
        if (amount > 0) balance += amount;
    }
    public static void main(String[] args) {
        BankAccount acc = new BankAccount();
        acc.deposit(500);
        System.out.println("Encapsulated Balance: " + acc.getBalance());
    }
}

Terminal Output:

Encapsulated Balance: 1500

9. Common Developer Pitfalls & Traps 🔝

Calling an Instance Method or Field Directly from static main()

Writing my_public(); or System.out.println(i); directly inside public static void main without an object fails with non-static method/variable cannot be referenced from a static context. Create an object with new first.

Uninitialized Object Reference: NullPointerException

Declaring my_first obj1 = null; and calling obj1.adder(); without calling new my_first() crashes at runtime with a NullPointerException.

10. Complete Compilable Java Program 🔝

public class OopClassFullDemo {
    static class Calculator {
        int add(int a, int b) { return a + b; }
        static int square(int n) { return n * n; }
    }
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        if (calc.add(12, 13) == 25 && Calculator.square(6) == 36) {
            System.out.println("All Java Class, Object & Method checks passed!");
        }
    }
}

Terminal Output:

All Java Class, Object & Method checks passed!

11. Frequently Asked Questions (FAQ) 🔝

What are the default values of class attributes if I don't initialize them?

Numeric attributes (like int j;) default to 0 (or 0.0), boolean attributes default to false, and object references (like String) default to null.

Can I create multiple objects from the same class?

Yes! Every call to new my_first() allocates an independent object on the heap with its own copy of non-static attributes (changing obj1.j never alters obj2.j).

What is the difference between a void method and a method with a return type?

A void method (like void adder()) performs an action without returning a value, whereas int adding(int x, int y) must end with a return statement of type int.

Can one .java file contain two classes?

Yes, as long as at most one of the top-level classes is declared public, and the filename matches that public class's name.

What are the four pillars of Java OOP?

Encapsulation (private fields + methods), Inheritance (extends), Polymorphism (method overriding), and Abstraction (abstract classes and interfaces).

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer