how to call an abstract class method? - java

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 ;)

Related

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.

Using "super" keyword or using a superclass instance when calling superclass methods locally in a method from subclass?

Let say I have:
class Superclass {
//fields...
methodA() {...}
methodB() {...}
...
}
class Subclass extends Superclass {
//fields...
methodA() {
// Here I need to call methods A and B from superclass:
// For this, I can use supper
super.methodA();
super.methodB();
// Or I have to instantiate the superclass and use the instance
Superclass superclass = new Superclass();
superclass.methodA();
superclass.methodB();
}
It works both ways, but I want to know which is better to use. Any of these ways is a bad programming technique? I hope you give me answer and arguments.
super.methodA();
Superclass superclass = new Superclass();
superclass.methodA();
These two calls of methodA work on different instances, so they are completely different. super.methodA() executes methodA on the current instance. superclass.methodA() executes methodA on a new instance of Superclass which is not related to the current instance.
You would almost always use the first option. As for the second option, It doesn't make sense to create a new instance, call a method on that instance and then never do anything with that instance again.
It works both ways, but I want to know which is better to use.
Well that entirely depends on what you're trying to achieve. If you want to create a new, entirely independent instance, do so. But it's more common that you want to use the superclass implementation of a method you're overriding on the same instance that the overridden method is currently executing on in which case you would use super.methodA().
In my experience, super is most commonly used when overriding a method to do some subclass-specific work, call the superclass implementation, then do some more superclass-specific work. For example:
#Override public void add(Foo foo) {
doSomeSubclassSpecificValidation(foo);
super.add(foo);
doSomeSubclassSpecificBookKeeping();
}
In other words, even though you're overriding the method, you still want the "normal" behaviour - you just want some extra code to run as well. Or sometimes you want to run the superclass code conditionally, e.g. only if the input meets a certain criterion.
It's totally different.
super.methodA() will call methodA() in the left circle, while creating a new superclass and calling that methodA() will first create the right circle, and then call methods from it.
With above answers, you must have understood that basically you are calling same method of same class but on two different objects so it all depends as what you are trying to achieve ( On which object you plan to call those methods ). As you know, call to same methods of same class but on different instances are not the same. "super" object is parent of "this" object and that super object was created implicitly when you instantiated Subclass so as per your example code, both are NOT SAME but for simple cases,output might be same. Go one more level up and see if it looks different to you from client code ( try writing calling code of Subclass ).

Obtain reference to Object calling superclasses method

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.

Calling functions without names in Java

I have a set of similar classes that all implement a function of the form
public static ClassA convertToClassA(Obj A)
public static ClassB convertToClassB(Obj B)
I want to loop through a list of classes and call this function that takes one argument of Obj in each class. How do I do this given each function is named differently?
Thanks for the help.
Class cls = Class.forName("ClassA");
String methodName = "convertTo" + cls.getSimpleName();
Method method = cls.getDeclaredMethod(methodName, new Class[]{Obj.class});
// If the underlying method is static, then the first parameter is ignored. It may be null as illustrated below.
method.invoke(null, your_object);
Create common interface with your method signature and let your invokable classes implement it, later on you can iterate over your objects as over instances of interface and call methods from it so no problem.
HOWEVER I am starting to think you want to call method without knowing it's name AT ALL - the only knowlage of target method is the number and type of arguments. Well that indeed IS impossible via reflection BUT, it will be innacurate if similar methods signatures will be present. Anyway, don't know what are you trying to do, but your project is badly designed from the ground (no interfaces, poor inharitance I guess etc.)
take a look at the reflection package. it provide methods to get back all the methods an instance has provide.
The apache common's BeanUtil (http://commons.apache.org/beanutils) also provide some util method doing similar things.

How to call a base class method without changing all derived classes

I have a class called Base which has a method called execute(). There are about 100 classes which derive from this base class and provide their own implementation of execute(). Now, I have some common logic which I want to put in Base.SomeMethod(). This method needs to be called at the end of execute(). My question whether it is possible to call this without changing each and every derived class's execute() method?
public class Base {
public final void execute() {
doExecute();
someMethod();
}
protected abstract void doExecute();
public void someMethod() {
}
}
This solution prevents the super code smell.
Yes, but you have to change the callers then. Callers will have to call a doExecute() (find a better name for it though) method, which you define in your base class as final, and which calls execute(), then the common code.
Another option is aspect-oriented programming, but I wouldn't recommend it for this purpose, that is, to "hack" code.
The question is: why is changing the name of a method in a 100 or so classes such a problem? It's a click of the mouse with an IDE.
Not that I'm aware of. Next time you should consider that you might want to add some common action for all extended classes, and call for super.execute()!
Only by using something that instruments your code; this isn't possible with pure Java.
Let me state your problem as i understand : Animal class has Breath() method which has implementation and due to inheritance all the subclasses has this member and unless there is very different way of breathing nobody will override.
Now at the end of Breath method you want to call CloseEyes() method of animal class and may be that is true that some or all of the subclasses overrides CloseEyes() method.
So your problem : Everytime any animal breath you want to them to CloseEyes but from Animal class and not from the derived classes.
If there are already CloseEyes() methods in many derived classes then you are actually doing something wrong in calling base class's CloseEyes().
If you still want only base class's method to be called then why do you need same method name- you just say AnimalEyeClose() , make it private and have it in Animal class.

Categories