关于OCL中self及属性调用allInstances()的合法性与等效性问询
allInstances() Usage in OCL Great question about a common point of confusion with OCL's allInstances()! Let's dive into this clearly, referencing the OCL 2.4 spec and practical tool behavior.
First, let's start with the formal definition from the OCL 2.4 specification: allInstances() is a static operation belonging to a classifier (like a class)—not an operation that instances of the class can call. So strictly speaking, syntax like self.allInstances() or somePerson.allInstances() isn't compliant with the official spec, because self and somePerson are instances of the class, not the class itself.
That said, many popular OCL tools implement a convenient syntax sugar that lets you call allInstances() on an instance. When you do this, the tool implicitly resolves it to instance.class.allInstances()—meaning it fetches all instances of the class that the instance belongs to.
Let's break down the scenarios to clarify when this might match <Type>.allInstances() and when it won't:
- Case 1: No inheritance, instance is a direct member of the class
Ifselfis an instance ofPersonand there are no subclasses ofPerson, thenself.allInstances()(if your tool supports it) will behave exactly likePerson.allInstances()—both return all instances of thePersonclass. - Case 2: Inheritance is involved
SupposeEmployeeis a subclass ofPerson, andselfis an instance ofEmployee. Then:self.allInstances()would return only instances ofEmployee(sinceself.classisEmployee),- while
Person.allInstances()returns all instances of bothPersonandEmployee(per OCL's handling of class hierarchies forallInstances()).
As for calling allInstances() via other attributes (like p.allInstances() where p is a Person-typed attribute), the same logic applies: it's dependent on the tool's syntax sugar support, and the result will be all instances of the class that p actually belongs to at runtime.
To avoid ambiguity and stay strictly compliant with the OCL 2.4 spec, it's always safest to use the explicit <Type>.allInstances() syntax (like Person.allInstances()) when you need all instances of a specific class.
内容的提问来源于stack exchange,提问作者user2680083

