Obtain reference to Object calling superclasses method - java

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?

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.

Related

Reference overridden method in supertype constructor

I'm trying to find a solution for a project assignment. Basically I have created a class which is derivative of another abstract class. In it's construction I'm trying to call the supertype constructor with a string and an integer as argument. The issue is that I'm trying to calculate the integer value in an overridden method in the same class. Like so:
super(name, getBaseValue());
This doesn't work because I can't reference the method within the supertype constructor. Maybe I have simply misunderstood the assignment and the UML-diagram. Any ideas how to go about solving this?
getBaseValue() must be static and also use this.getBaseValue (), so that it looks like this:
super(name, this.getBaseValue());
You probably shouldn't do that at all. At the time the constructor runs, the object is not yet created (it's still in the process of being created), and calling a method on it is risky because that method may assume the object is fully created. Even worse, a derived class could also define that method, and then you the parent constructor isn't even done when a child class' method is already called --- chaos.
You can call static methods (which don't require an object instance being created), or you can hard-code any values you want to pass.
See also MET05-J. Ensure that constructors do not call overridable methods in the Secure Java Coding Standard and Sonar Source's warning about this.

Which method is called when Object is typecasted to parent

I know that this must have been asked before, but I'm not sure how to search for this.
If I have a Object of class B that extends class A, If I type cast this object to class A and then call a overriden method on this object, which method will be called? A's or B's?
The real class of an object determines with methods are called.
Those casts, and types that you are using in your source code are not really meaningful at runtime. You rather look at them as a way to enable human coders to do their job.

Should I make 'count' as static in derived class, how to access it

I have a class, lets say CargoShip, which is a derived class of 'Starcraft', which implements the interface IStarcraft.
This is the function that should return the count (number of instances) of every ship:
public static void printInstanceNumberPerClass (ArrayList<ISpacecraft> fleet){}
There's a solution which I thought of and I'm sure it will work, declaring 'getCount()' in ISpacecraft, then overriding it in each SpaceCraft ship (I have 4 ships), and just iterating through everyone of them, polymorphism.
Fine, I got that. but because the function is static (yes, I know we dont need to create an object to use it) I thought it might tell me something different. What do I mean by that? Is it possible to create 'static count = 0' instead, in every ship, and somehow access it?
The question is then, how can I access that static field when I get an arraylist of ISpacecraft objects?
Polymorphism doesn't work with static methods, method resolution is very different. For virtual methods on an instance the code may be referring to the object with a variable typed as a superclass or interface, and calling a method is resolved at runtime without your application code needing to know the exact concrete type. For static methods you call it on a specific class and if the method isn't found then it's called on a superclass. Your code has to start with some subclass and resolution works up the hierarchy from there. For static methods you can't not know a low-level class to call the method on, the way you can with instance methods on objects. You can't have the level of abstraction you take for granted with objects.
The comment by markspace provides a much better alternative. Use static methods for stateless functions like java.lang.Math.

how to call an abstract class method?

I am trying to create an R function that taps into my JAVA code.
I have an abstract class, let's say StudentGroup, that has abstract methods, and one method getAppropriateStudentGroup() which returns (based on config) a class which extends StudentGroup. This allows calling classes to behave the same regardless of which StudentGroups is actually appropriate.
How can I use rJava to call getAppropriateStudentGroup()?
How can I call the methods on the returned class?
Thank you!
Java won't let you call an instance method unless you first have an instance. Naturally, you can't instantiate an abstract class, so, to the best of my knowledge, you'll have to declare getAppropriateStudentGroup() static and call it like so: StudentGroup.getAppropriateStudentGroup().
I'm assuming you actually pass some parameters to getAppropriateStudentGroup() or you'll always get the same.
Option B, I misunderstood you, and you actually do have instances of something that extends the abstract class StudentGroup, in which case you should be able to call that method on the object without problems.
I think something's a bit confused in your question or my answer, please write back ;)

Referring to "this" while invoking super constructor?

I have a class A and write a subclass B. A has only one constructor which is parameterised. B has to call this super constructor of A.
Now I want to use an Object as a parameter. This object should call a method of B. So the parameter-object has to hold a reference of B or has to be an inner class.
public B(){
super.(new parameter(this))
}
Now when I want to invoke the constructor like... Eclipse says:
Cannot refer to 'this' nor 'super' while explicitly invoking a constructor
The only thing I see to get around this, is a set-method, to inject the "this"-instance into the parameter object. I would not like to edit the super-class.
Do you see any better way around this.
The compiler is really preventing you from shooting yourself in the foot here. B isn't fully constructed until after the call to the super constructor, so if you pass this (if the compiler allowed it) as a reference, and it calls a method on B, B would be in an invalid state and cause all kinds of nasty problems (in fact, A is still not initialized, nor any class up the chain, including Object).
The obvious solution is to provide the functionality outside of B and pass that to the constructor of the parameter. Specific solutions will depend on the specific problem, but a static nested class inside B (it needs to be static for the same reason - an inner class has an implicit reference to the outer class instance) could provide that functionality, perhaps. Maybe you need to rethink the relationship between the parameter, B and its super class. It all depends on the case.

Categories