Object Oriented

Special Method

Java

 

Constructor

Java 8
class Person {
  
  public String name;
  public int age;
  
  public Person(String name, int age) {
    this.name = name;
    this.age = age;
  }
  
}

Classes that have a Constructor method call this method on each newly-created object.

This method is suitable for any initialization that the object may need before it is used.

Here you can pass name and age when instantiating a Person object.

Person person1 = new Person("Sam", 25);
 

Destructor

Java 8
class Person {
  
  // ...
  
  @Override
  protected void finalize() throws Throwable {
    try{
        System.out.println("finalize method called");
    }finally{        
        super.finalize();
    }
  }
  
}

finalize is a method that the Garbage Collector calls just before destroying that class object.

finalize is the closest thing to Destructor in Java.

 

Getter

Java 8
class Person {
  
  public String fname;
  public String lname;
  
  public String fullname() {
    return fname + " " + lname;
  }
  
}

There is no special syntax for Getter methods in Java.

Person person1 = new Person();
person1.fname = "Sam";
person1.lname = "Winchester";

String fullname = person1.fullname(); // Sam Winchester
 

Setter

Java 8
class Person {
  
  public String fname;
  public String lname;
  
  public void fullname(String str) {
    String[] names = str.split(" ");
    fname = names[0];
    lname = names[1];
  }
  
}

There is no special syntax for Setter methods in Java.

Person person1 = new Person();
person1.fullname("Sam Winchester");

String firstname = person1.fname;  // Sam
String lastname = person1.lname;   // Winchester
 

toString

Java 8
class Person {
  
  public String name;
  public int age;
  
  @Override
  public String toString() {
    return name + " is " + age;
  }
  
}

toString is called whenever a string representation of the object is needed.

Person person1 = new Person();
person1.name = "Sam";
person1.age = 25;

System.out.println(person1);  // Sam is 25