2

What is the difference between

setBorder(new TitledBorder(""));

and

setBorder(BorderFactory.createTitledBorder(""));

and which advantages/disadvantages do they have?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Big_Chair
  • 2,781
  • 3
  • 31
  • 58

2 Answers2

4

BorderFactory actually might not create new instances each time you call it, but return a reference to an existing one, therefore saving some resources. See also the javadoc.

You can also check out the actual implementation if you really want to know what's going on inside BorderFactory ;-)

Blub
  • 3,762
  • 1
  • 13
  • 24
1

According to Effective Java, item-1: Consider static factory methods instead of constructors. BorderFactory.createTitledBorder("") is static factory method which has following advantages:

  1. One advantage of static factory methods is that, unlike constructors, they have names.
  2. A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  3. A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  4. A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

For details descriptions, go through the Book.

Masudul
  • 21,823
  • 5
  • 43
  • 58
  • The item is put for letting us know to think while implementing such. But with already implemented class, we must know why actually they were done for this specific class. – Sage Dec 08 '13 at 21:27