Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

oops Method → Method in oops

oops Method

Method in oops

Methods in OOP:

In OOP, methods define the actions that objects can perform. Methods can take arguments, just like functions, and they can also return values. This allows objects to interact with other objects and perform complex tasks within a program. A method is a collection of statements that perform some specific task and return the result to the caller. A method can perform some specific task without returning anything. Methods allow us to reuse the code without retyping it, which is why they are considered time savers. Static Methods: A static method is a method that belongs to a class, but it does not belong to an instance of that class. This method can be called without the instance or object of that class. Static methods are associated with the class itself rather than with individual instances. They are allocated memory only once, at the time of class loading. Static methods can be accessed directly using the class name followed by the method name (e.g., ClassName.memberName). They can only access other static members within the same class. Static methods are commonly used for utility methods, constants, or variables that are not specific to individual instances.
Static method example public class Helper { public static int sum(int a, int b) { return a + b; } }
Non-Static Methods: Every method in Java defaults to a non-static method without the static keyword preceding it. Non-static methods are specific to each instance of a class, as they are tied to objects created from the class. They have memory allocated separately for each instance of the class4. Non-static methods are accessed using an object reference followed by the member name (e.g., objectReference.memberName). They can access both static and non-static members within the same class. Non-static methods are used for instance-specific behavior, as they hold data specific to each object.
non-static method public class Helper { public int sum(int a, int b) { return a + b; } }
These are the fundamental concepts of methods, static and non-static methods in Java. Each of these concepts provides a different way to structure and organize your code.