Interview Prep Flashcards
Things to do during or before an interview
What are the advantages of using static facotry methods instead of constructors for creating objects
factory methods can have names unlike constructors which are restricted to the name of the class
You can have multiple factory methods with different names and the same type and number of arguments that do different thing
For example
static createPoint (int x., int y)
{
new Point(x, y)
}
public static Point createPointCartesian(int x, int y)
{
return new Point(2x, 2y) // for example
}
In the above example the FM could return any other class also
createPointCartesian(int x, int y)
{
return new CartesianPoint(2x, 2y) // for example
}
as long as CartesianPoint is a subclass of Point
Usually when used instead of constructors. the constructors are made private..
In case returning subclass type. the subclass constructors does need to be public
Another Advantage is the static facotry does not need to create a new object all the time. They may return an existing object …cached object . Kind of like Flyweight which can then return an common object.
Example of Builder pattern .. this also uses factory method
package javachallengers;
public class Person {
private final String name;
private final String surname;
private final String title;
private final String address;
Person(String name, String surname, String title,String address) { this.name = name; this.surname = surname; this.title = title; this.address = address; } public static Builder builder(String name,String surname) { return Builder.of(name, surname); } static class Builder { private final String name; private final String surname; String title; String address; public Builder(String name,String surname){ this.name = name; this.surname = surname; } public static Builder of(String name,String surname) { return new Builder(name, surname); } public Builder setTitle(String title) { this.title = title; return this; } public Builder setAddress(String address) { this.address = address; return this; } public Person build() { // since at this point there is no gurrante that all values have been set.. you can check properties and do validation here return new Person(name, surname, title, address); } } public static void main(String[] args) { Person person = Person.builder("name","surname").setAddress("address").setTitle("title").build(); } }
Immutability
Enums
Streams