Page 355 - CITS - Computer Software Application -TT
P. 355
COMPUTER SOFTWARE APPLICATION - CITS
Example
Create a method inside Main:
public class Main {
static void myMethod() {
// code to be executed
}
}
Example Explained
• My Method() is the name of the method
• Static means that the method belongs to the Main class and not an object of the Main class. You will learn
more about objects and how to access methods through objects later in this tutorial.
• Void means that this method does not have a return value.
Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
public class Main {
static void myMethod() {
System.out.println(“I just got executed!”);
}
public static void main(String[] args) {
myMethod();
}
}
// Outputs “I just got executed!”
Java Object as Parameter
Objects, like primitive types, can be passed as parameters to methods in Java. When passing an object as a
parameter to a method, a reference to the object is passed rather than a copy of the object itself. This means that
any modifications made to the object within the method will have an impact on the original object.
public class MyClass {
// Fields or attributes
private int attribute1;
private String attribute2;
private double attribute3;
// Constructor
public MyClass(int attribute1, String attribute2, double attribute3) {
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.attribute3 = attribute3;
342
CITS : IT&ITES - Computer Software Application - Lesson 94 - 100