|
-
Feb 25th, 2006, 09:51 AM
#1
Thread Starter
Lively Member
Why is this happening?
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.
-
Feb 25th, 2006, 12:14 PM
#2
Re: Why is this happening?
you must use the method "Object.equals" istead of "=="
becuase "==" compares values to references
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Feb 25th, 2006, 06:14 PM
#3
-
Feb 25th, 2006, 08:53 PM
#4
Re: Why is this happening?
 Originally Posted by manavo11
You could also do something like this :
Code:
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
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
Feb 26th, 2006, 05:13 PM
#5
-
Feb 26th, 2006, 05:53 PM
#6
Frenzied Member
Re: Why is this happening?
 Originally Posted by manavo11
You could also do something like this :
Code:
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
-
Feb 26th, 2006, 06:07 PM
#7
Re: Why is this happening?
 Originally Posted by manavo11
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 (Added unnecessary operations) and Space (Defined unnecessary variables)
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|