What is this called?
This is a 开发者_开发问答constructor from the Bits
class from JBitTorrent API. It is perfectly valid:
public Bits and(Bits b){ /* something */ }
But there's a space in the method name. So whas is this called? I thought is "java multimethod" but it's not.
It's not a constructor, it's a regular Java method.
The first Bits
is the return type, and and
is the method name.
If it were a constructor, it would not have a return type, and the name would be the name of the class it is constructing.
The method may be constructing a new Bits
instance and returning it, but it's still a method.
It's not a constructor and there's no space in the method name.
The method is called and
, it takes a Bits
object as the argument and it returns a Bits
object.
It's a normal method with there's no particular name for this (from the language perspective).
It's a common pattern, usually used for immutable objects: instead of modifying the object on which the method is called, a new object is created with the modified state (this can also be done on mutable objects, but is more common with immutable ones).
Where do you think you see a space in the method name?
public Bits and(Bits b){ //something }
It is a public
method named and
that returns a Bits
object, and that takes a Bits
object as an argument (with the argument variable named b
).
It is not a constructor, just a regular method.
but there's a space in the method name
No there isn't. The method name is "and". Bits
is the return type!
There's not a space in the method, the method name is "and".
public
- modifierBits
- return valueand
- method nameBits b
- a parameter b of type Bits
Usually used in a Builder pattern (e.g. StringBuilder) where fields/operations are provided to create a fully constructed object.
The public Bits and(Bits b) {...}
is not a constructor but method that requires a Bits b
in order to change the state of the current internal bits (ANDed).
The implementation would be of this effect.
public Bits and(Bits b) {
this.doAnd(b);
//Now that our internal bits are ANDed with bits B, return our changed state
return this;
}
精彩评论