Object Oriented

Method

Java

 

Defining Method

Java 8
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)

 

Method Parameters

Java 8
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.

 

Invoking Methods

Java 8
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.

 

Invoking Methods from inside Class

Java 8
class Person {
  
  // ...
  
  public void birthday() {
    this.setAge(getAge() + 1);
  }
  
}

Methods can be accessed from inside a class just by using the method name or explicitly by calling it on this.