PDA

Click to See Complete Forum and Search --> : Why is this happening?


Sebouh
Feb 25th, 2006, 08:51 AM
Hi. I am having this problem. I know the solution but i want to know why the problem happened?

i have this:
if (obj.getClass() == Student.getClass())
Student temp = (Student)obj;

I get a compilation error, non-static methode getClass() cannot be referenced from a static context.

i am using this code instead of: if (obj instenceof Student)
When i use: if (obj.getClass() == getClass()) i don't have a problem.
So can anyone please explain what the error means? Why is it saying i am calling from a static context. the method this code is in is not static. i am calling it from the equals method in the Student class.

thanks.

ComputerJy
Feb 25th, 2006, 11:14 AM
you must use the method "Object.equals" istead of "=="
becuase "==" compares values to references

manavo11
Feb 25th, 2006, 05:14 PM
You could also do something like this :

String classname=new String(P.getClass().getName());
if (classname.compareTo("Student")==0) {
...

ComputerJy
Feb 25th, 2006, 07:53 PM
You could also do something like this :

String classname=new String(P.getClass().getName());
if (classname.compareTo("Student")==0) {
...
There are so many ways to do this but yours is the worst

Congratulations on the promotion by the way

manavo11
Feb 26th, 2006, 04:13 PM
There are so many ways to do this but yours is the worst

Congratulations on the promotion by the way
Where did I say that it's the best way to do it? All I know is that it will work, I'm sure there are better ways to do it. Why is it the worst? And what promotion?

System_Error
Feb 26th, 2006, 04:53 PM
You could also do something like this :

String classname=new String(P.getClass().getName());
if (classname.compareTo("Student")==0) {
...

Looks good to me. You could actually override the compareTo() method and make it even more powerful in this case (in my opinion). It returns an int so you could deal with several different cases and it can also raise error messages that .equals() would simply shun aside by returning false.... I don't know if that's a plus or a minus ;)

ComputerJy
Feb 26th, 2006, 05:07 PM
Where did I say that it's the best way to do it? All I know is that it will work, I'm sure there are better ways to do it. Why is it the worst?

I know you didn't say, I just notified you it's the worst way
because your not considering Time :confused: (Added unnecessary operations) and Space :confused: (Defined unnecessary variables)