Question

I am trying to write an abstract class. In that class I have a method which is supposed to access the actual object for which the method is called. "this" however will only return the "part of the object" that I write myself (the abstract one).

To specify some more: If the method I was writing had a parameter of the type of my class, what i want looks like this:

public abstract class MyClass {
  public void foo(MyClass invoker) {
    ...
  }
}

The above code would allow me access to the object invoking the method, but it would be tedious to write it like this, since this is supposed to become part of a library I want to supply to others and I cannot know for certain, that the passed argument would in fact be the right object and not some other object of a class derived from MyClass.

Is there a way to invoke something along the lines of getNestingObject() or do I specifically have to give the method a parameter and constantly infer "this" to every call?

Finally, since I am no master in java, a perhaps less obvious question: Is there a security reason, why the above described concept is flawed? Could someone with malicious intent abuse that kind of keyword?

Was it helpful?

Solution

I am trying to write an abstract class. In that class I have a method which is supposed to access the actual object for which the method is called. "this" however will only return the "part of the object" that I write myself (the abstract one).

this will return a reference to "the whole" object, not "a part". To proof this, if you cast this reference to a class that is lower in the hierarchy, you can access any property or method of this class using the instance referenced by this.

However, casting the instance referenced by this, would not be a good design practice. Speaking in general terms, you should write a foo method in MyClass with the general behaviour, and override it with the particular behaviour of each classs. If you want to use the foo method of the parent class, you can invoke it using super.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top