Identifying calling object
Hey guys!
I'm trying to do this:
Code :
int x;
x = orc.getFrags; //orc extends player
In class player I have:
Code :
public int getFrags(){
If (this.getClass().getName().equals("orc")){
return 5;
}
}
But it doesn't work. I'm guessing its because "this" returns the class player and not the subclass orc. Is there any way to determine which object/subclass called a method from a superclass?
Re: Identifying calling object
Add a println in the getFrags method to print the class name, you will then see which class it is referring to, and what the name actually is.
Re: Identifying calling object
It does indeed return the class "player". Is there any way to find out if the method was called with regards to a subclass like orc, elf etc?
Re: Identifying calling object
Quote:
Originally Posted by
frogfury
It does indeed return the class "player". Is there any way to find out if the method was called with regards to a subclass like orc, elf etc?
This is not the behavior on my machine. Is orc just a reference to an instance of Player, or is it actually a class which extends Player? What exactly are you trying to accomplish
Code java:
public class Test{
public static void main(String[] args) throws Exception{
Player pla = new Temp();
pla.getFrags();
}
private static class Player {
public void getFrags(){
System.out.println(this.getClass().getName());
}
}
private static class Temp extends Player{
}
}
Prints out Temp, not Player
Re: Identifying calling object
Apart from all that, if you need to know which subclass's method is invoked, it's almost always a sign of misuse of inheritance.
db
Re: Identifying calling object
Reading copeg's example I just realized that I had set my main class to private. No wonder it wasn't working...
Thanks a lot for your time guys!:-bd
Re: Identifying calling object
Quote:
Originally Posted by
Darryl.Burke
Apart from all that, if you need to know which subclass's method is invoked, it's almost always a sign of misuse of inheritance.
db
^^ this is very important to keep in mind, as this is the basis for creating well-formed polymorphic classes, as well as properly using inheritance.
If you want a way to differentiate the name of different players, put a string field in your base class.
Code Java:
public abstract class Player
{
public final String name;
public Player(String name)
{
this.name = name;
}
}
Code Java:
public class Orc extends Player
{
public Orc()
{
super("orc");
}
}
Code Java:
public static void main(String[] args)
{
Player p1 = new Orc();
Player p2 = new Wizzard(); // code for Wizzard not provided, but it's something similar to Orc
System.out.println(p1.name);
System.out.println(p2.name);
}
If you have a set list of names possible, simply use an enumeration instead of a string.