Object Oriented
Method
Java
class Person {
public void greet() {
System.out.println("Hi!");
}
}
Methods are actions performed on objects.
Methods may get some input and may return a value. If method is not returning anything, it should be specified with void
.
The public
keyword defines the visibility of the Method. (Check Visibility Topic for more on this)
class Person {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sleep(int from, int duration) {
String output = getName() + " slept from " +
from + " for " + duration + " hours.";
System.out.println(output);
}
}
Parameters are inputs to methods.
Parameters are separated by comma (,
).
Parameters have types, just like variables.
Parameters of primary types are passed by value.
Parameters of type array or object are passed by reference.
Person person1 = new Person();
person1.setName("Sam");
String name = person1.getName(); // Sam
person1.sleep(10, 7); // Sam slept from 10 for 7 hours.
Methods of an object can be accessed like any properties on it.