纯方法是否必须为static?实例方法可被定义为纯方法吗?
Great question! Let's unpack this using your Rational example and the core definition of pure methods.
First, let's recap the key traits of a pure method:
- Its return value depends only on its inputs (no hidden state or external data)
- It has no side effects (no modifying state, printing, I/O, etc.)
- Calling it multiple times with the same inputs will always give the same result
Your example breakdown
Your static toDouble(Rational rational) method is clearly pure: it takes a Rational as an explicit parameter, uses only its internal state (numer/denom), has no side effects, and returns a consistent value for the same input.
Now, what about the non-static toDouble() instance method? Let's look at what it's actually doing:
public double toDouble() { double x = this.numer; double y = this.denom; double fprat = x / y; return fprat; }
This method relies on the this reference—an implicit parameter that points to the instance the method is called on. If we treat this as just another input (which it effectively is), then this method meets all the pure method criteria as long as the Rational instance is immutable.
In your current Rational class, there are no methods to modify numer or denom after instantiation. That means once a Rational object is created, its state never changes. So calling toDouble() on the same instance will always return the same value, with no side effects. By that standard, this instance method is absolutely a pure method.
Addressing the textbook definition
The textbook defines pure methods as "static methods that only depend on parameters, not other data"—this is a simplified explanation, not the strict universal definition. It's likely using static methods to avoid the complexity of explaining this as an implicit parameter. But in reality, pure methods don't have to be static.
When would an instance method NOT be pure?
If your Rational class had mutable state (e.g., a setNumer(int) method that changes the instance's numer value), then calling toDouble() on the same instance could return different results over time. In that case, the method would depend on mutable external state and wouldn't be pure.
Final takeaway
Non-static instance methods can absolutely be pure methods if:
- They don't modify any state (including the instance's own state) or produce side effects
- Their return value depends only on the implicit
thisparameter and any explicit parameters - The instance (and any other inputs) are immutable (or their state doesn't change between calls)
In your specific example, both toDouble() implementations are pure methods—they just differ in how they receive their input (explicit parameter vs. implicit this reference).
内容的提问来源于stack exchange,提问作者Josh Hardman

