views:

48

answers:

3

I wonder if there's a way to define a class in such a way that instances of it will never be members of another class (only local variables), or the other way round - only members but never local.

Is there any way in which a class can dictate the scope of it's prospective instances?

+2  A: 

I don't think so. But I have no definitive proof.

Ron Tuffin
+1  A: 

To limit the scope you'd some sort of class annotation or class modifier and the virtual machine needed the functionality to check, whether a class (or any subclass of this restricted class) was assigned to a member or local variable and violated the constraint.

Just imagine, you had a class with the - just invented - 'onlylocal' modifier, indicating that you only allow instances in local variables.

public onlylocal class LocalUseOnlyClass implements Serializable {
  //...
}

and in another class someone just did in a constructor:

private Object member;
public MyOtherClass(Serializable something) {
  this.member = something
}

The Compiler couldn't detect, if you passed an instance of LocalUseOnlyClass to that constructor, so the JVM had to check and throw an exception or an error.

BTW & OT: what's your intention? - maybe there's an alternative to fulfill your underlying requirement.

Andreas_D
+1  A: 

no. member and local variable can be assigned to each other.

irreputable