You can define the compareTo method in a class without implementing the Comparable interface. What are the benefits of implementing the Comparable interface?
9009
So lets say I have this interface:  public interface IBox {    public void setSize(int size);    public int getSize();    public int getArea();   //...and so on }   And I have a class that implements it:  public class Rectangle implements IBox {    private int size;    //Methods here }   If I wanted to use the interface IBox, i can't actually create an instance of it, in the way:  public static void main(String args[]) {     Ibox myBox=new Ibox(); }   right? So I'd actually have to do this:  public static void main(String args[]) {     Rectangle myBox=new Rectangle(); }   If that's true, then the only purpose of interfaces is to make sure that the class which implements an interface has got the correct methods in it as described by an interface? Or is there any other use of interfaces?
1905
I ran into an interesting (and very frustrating) issue with the equals() method today which caused what I thought to be a well tested class to crash and cause a bug that took me a very long time to track down.   Just for completeness, I wasn't using an IDE or debugger - just good old fashioned text editor and System.out's. Time was very limited and it was a school project.  Anyhow -   I was developing a basic shopping cart which could contain an ArrayList of Book objects. In order to implement the addBook(), removeBook(), and hasBook() methods of the Cart, I wanted to check if the Book already existed in the Cart. So off I go -  public boolean equals(Book b) {     ... // More code here - null checks     if (b.getID() == this.getID()) return true;     else return false; }   All works fine in testing. I create 6 objects and fill them with data. Do many adds, removes, has() operations on the Cart and everything works fine. I read that you can either have equals(TYPE var) or equals(Object o) { (CAST) var } but assumed that since it was working, it didn't matter too much.  Then I ran into a problem - I needed to create a Book object with only the ID in it from within the Book class. No other data would be entered into it. Basically the following:  public boolean hasBook(int i) {     Book b = new Book(i);     return hasBook(b); }  public boolean hasBook(Book b) {     // .. more code here     return this.books.contains(b); }   All of a sudden, the equals(Book b) method no longer works. This took a VERY long time to track down without a good debugger and assuming the Cart class was properly tested and correct. After swaapping the equals() method to the following:  public boolean equals(Object o) {     Book b = (Book) o;     ... // The rest goes here    }   Everything began to work again. Is there a reason the method decided not to take the Book parameter even though it clearly  was  a Book object? The only difference seemed to be it was instantiated from within the same class, and only filled with one data member. I'm very very confused. Please, shed some light?
86053
Is there any advantage to using the older testMethod keyword to identify test methods or is it better to use the @IsTest annotation?  Does the location of these test methods have any significance? E.g. Either being included within the definition of the class being tested or defined in a separate class.
11352
Duplicate:     Maybe this is a very silly question but I don't understand why I can't declare two methods that have the same signature when they have different return types.  public class MyClass {     private double d = 0;      public double MyMethod()     {         return d;     }      public string MyMethod()     {         return d.ToString();     } }   I get a compile error that states that the class already defines a member with the same parameter types.  (Obviously the way I'm using this in my code isn't as simple as my example code...but I think it gets the idea across.)  Am I missing something concerning OO design that makes what I'm trying to do an OOP anti-pattern? Surely the compiler should be able to determine which method I'm trying to use as long as I specifically tell it which one I want.  Given MyClass myClass = new MyClass(); I would expect the following code to work:  double d = myClass.MyMethod(); string s = myClass.MyMethod();   I would expect the following code to have problems:  var v = myClass.MyMethod();   But even in the case of var it should result in a compile error.  Can anyone see what I'm doing wrong here? I'm more than happy to be corrected. :-)
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
29529
I am a big fan of letting the compiler do as much work for you as possible.  When writing a simple class the compiler can give you the following for 'free':   A default (empty) constructor A copy constructor A destructor An assignment operator (operator=)   But it cannot seem to give you any comparison operators - such as operator== or operator!=.  For example:  class foo { public:     std::string str_;     int n_; };  foo f1;        // Works foo f2(f1);    // Works foo f3; f3 = f2;       // Works  if (f3 == f2)  // Fails { }  if (f3 != f2)  // Fails { }   Is there a good reason for this?  Why would performing a member-by-member comparison be a problem?  Obviously if the class allocates memory then you'd want to be careful, but for a simple class surely the compiler could do this for you?
105044
This might be a old question: Why does IEnumerable&lt;T&gt; inherit from IEnumerable?  This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable&lt;T&gt;, I have to write two GetEnumerator() functions, one for IEnumerable&lt;T&gt; and the other for IEnumerable.  And, IList&lt;T&gt; doesn't inherit from IList.   I don't know why IEnumerable&lt;T&gt; is designed in other way.
22377
Some time ago, I came across a piece of code, that used some piece of standard Java functionality to locate the classes that implemented a given interface. I know the functions were hidden in some non-logical place, but they could be used for other classes as the package name implied. Back then I did not need it, so I forgot about it, but now I do, and I can't seem to find the functions again. Where can these functions be found?  Edit: I'm not looking for any IDE functions or anything, but rather something that can be executed within the Java application.
19919
I ran into an interesting behavior recently.  It seems that if I override .equals() to take a parameter other than Object, it doesn't get called.  Can anyone explain to me why this is happening?  It seems to violate my understanding of polymorphism in OOP, but maybe I'm missing something.  Here's much simpler code that shows what I'm seeing:  public class MyClass {   private int x;   public MyClass(int n) { x = n; }   public boolean equals(Object o) { return false; }   public boolean equals(MyClass mc) { return x == mc.x; }   public static void main(String[] args) {     List&lt;MyClass&gt; list = new ArrayList&lt;MyClass&gt;();     list.add(new MyClass(3));     System.out.println("Contains 3? " + list.contains(new MyClass(3)));   } }   When this is run, it prints "Contains 3? false".  It looks like the equals(Object) function is called, even though there is another that would work.  By contrast, if I write equals like this the code works as expected:  public boolean equals(Object o) {   if(!(o instanceof MyClass))     return false;   MyClass mc = (MyClass)o;   return x == mc.x; }   Why isn't it figuring out which version of the function to call based on the type of the parameter?
72761
I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?
40034
Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?  Isn't Complex a, b, c; a = b + c; much simpler than Complex a, b, c; a = b.add(c);?  Is there a known reason for this, valid arguments for not allowing operator overloading? Is the reason arbitrary, or lost to time?
14961
This may be a generic OOP question. I wanted to do a generic comparison between an interface and an abstract class on the basis of their usage.   When would one want to use an interface and when would one want to use an abstract class?
22356
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?    string testString = "Test"; string anotherString = "Another";  if (testString.CompareTo(anotherString) == 0) {} if (testString.Equals(anotherString)) {} if (testString == anotherString) {}   (Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)
7409
Should a method that implements an interface method be annotated with @Override?  The  says:      Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.   I don't think that an interface is technically a superclass. Or is it?
39452
Why was C# designed this way?  As I understand it, an interface only describes behaviour, and serves the purpose of describing a contractual obligation for classes implementing the interface that certain behaviour is implemented.  If classes wish to implement that behavour in a shared method, why shouldn't they?  Here is an example of what I have in mind:  // These items will be displayed in a list on the screen. public interface IListItem {   string ScreenName();   ... }  public class Animal: IListItem {     // All animals will be called "Animal".     public static string ScreenName() {         return "Animal";     } .... }  public class Person: IListItem {      private string name;      // All persons will be called by their individual names.     public string ScreenName() {         return name;     }      ....   }
96218
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)  Class ReportClass {  public string ReportName {get; set;} }   Then it was used as follows in code:  displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())   That is about the simplest form example I can give you. Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?  EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today
43
I am working on an application and one design approach involves extremely heavy use of the instanceof operator. While I know that OO design generally tries to avoid using instanceof, that is a different story and this question is purely related to performance. I was wondering if there is any performance impact? Is is just as fast as ==?  For example, I have a base class with 10 subclasses. In a single function that takes the base class, I do checks for if the class is an instance of the subclass and carry out some routine.   One of the other ways I thought of solving it was to use a "type id" integer primitive instead, and use a bitmask to represent categories of the subclasses, and then just do a bit mask comparison of the subclasses "type id" to a constant mask representing the category.  Is instanceof somehow optimized by the JVM to be faster than that? I want to stick to Java but the performance of the app is critical. It would be cool if someone that has been down this road before could offer some advice. Am I nitpicking too much or focusing on the wrong thing to optimize?