5. Java Methods
5. Java Methods
OBJECT ORIENTED
PROGRAMMING I RCS 122
Example:
sayHello() // user define method created above in the article
myGreeting()
setName()
Different ways to create User-defi ned methods
a. Static Method:
They can be executed even if there are no objects
created.
They cannot operate on (reference to) instance variables.
This is because instance variables may not be created.
Hence, there is no need to create an object to call it, and
that’s the most significant advantage of static methods.
Declared inside class with static keyword.
Example: // Static Method
public static void method_name() {
// static method body
}
User-defi ned methods- Static method(Cont..)
Example
Create a method inside Main:
public class Main {
public static void myMethod() {
// code to be executed
}
}
myMethod() is the name of the method
static means that the method belongs to the Main
class and not an object of the Main class hence no
need to create objects.
void means that this method does not have a return
Calling Methods (Cont..)
To call a method in Java, write the method's name followed
by two parentheses () and a semicolon inside the main
method;
In the following example, myMethod() is used to print a text
(the action), when it is called:
Example Inside main, call the myMethod() method:
public class Main {
public static void main(String[] args) {
myMethod();
}
static void myMethod() {
System.out.println("I just got executed!");
}
}
Methods (Cont..)
A static method with void return type
Example:
// Instance Method
public void method_name() {
// instance method body
}
Creating Objects
In Java, an object is created from a class. For
instance, if you create the class named Main, you
can use this class to create objects.
To create an object of Main, specify the class name,
followed by the object name, and use the
keyword new:
Syntax
ClassName objectName = new ClassName();
Thus, the object from the class Main will be :
Main myObj = new Main();
You can create multiple objects of one class
Calling Instance methods using Objects
int num1 = 5;
A method called
A class called MyClass
myMethod
int x; p e An instance
ty
p e x = 10; u r n method with
ty le e t r n t
t
a a
a b r
return x; t u en a non-void
D a ri r e te m
v } t a return-type
A s
public static void main(String args[]) {
MyClass obj = new MyClass ();
The main
method
b je c t System.out.println(obj.
An o
myMethod());
}
}
b. Instance Methods (Cont..)
public class Subtractor {
public static void main(String[] args) {
// Create an object (instance) of the Subtractor class
Subtractor subtractorObject = new Subtractor();
CONSTRUCTORS
THANK YOU!