Abstract Class that implements Comparable

I am trying to understand how a comparable interface works with an abstract class. Any help is greatly appreciated.
I have a class ClassA defined as follows:
public abstract class ClassA implements Comparable I have a method, compareTo(..), within ClassA as follows:
public int compareTo(Object o) I have a sub-class ClassB defined as follows:
public class ClassB extends ClassAI am receiving a compile error:
Class must implement the inherited abstract method packagename.ClassA.compareTo(Object)
Should or can the compareTo be abstract in ClassA and executed in ClassB? Just not sure how this works.

???? if you are inheriting from an abstract class your subclass must implement methods that were declared in the parent (abstract) class but not implemented
When in doubt, refer to the Java Language Specification..

Similar Messages

  • Compile-time warning during javac of a Class that implements Comparable

    Hello All,
    I have defined a class as follows;
    public class CardTiles extends JButton implements Comparable{
    During normal compilation with javac, it tell me to use Xlint to compile and the warning it throws is below:
    CardTiles.java:4: warning: [serial] serializable class CardTiles has no definition of serialVersionUID
    public class CardTiles extends JButton implements Comparable{
    ^
    1 warning
    What does this warning mean?
    Many thanks!

    ejp wrote:
    you can choose to to differentiate between various versions of your CardTiles classThat's back to front. Serialization will always do that unless you stop it, which you can do via a fixed serialVersionUID. This tells Serialization that different versions of your class are compatible under serialization.I suppose I see it this way because I wouldn't have a serializable object without an ID. Without having an explicit ID the process isn't as transparent to me. It's the same sort of thing as using braces for statements when they're not necessary, e.g.
              if(check)
                   System.out.println("check is on");
              else
                   System.out.println("check is off");     versus     
              if(check) {
                   System.out.println("check is on");
              } else {
                   System.out.println("check is off");
              }

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Serializing a class that implements the Singleton pattern

    Hello,
    I am relatively new to Java and especially to serialization so the answer to this question might be obvious, but I could not make it work event though I have read the documentation and the article "Using XML Encoder" that was linked from the documentation.
    I have a class that implements the singleton pattern. It's definition is as follows:
    public class JCOption implements Serializable {
      private int x = 1;
      private static JCOption option = new JCOption();
      private JCOption() {}
      public static JCOption getOption() { return option; }
      public int getX() { return x; }
      public void setX(int x) { this.x = x; }
      public static void main(String args[]) throws IOException {
        JCOption opt = JCOption.getOption();
        opt.setX(10);
        XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("Test.xml")));
        encoder.setPersistenceDelegate(opt.getClass(),  new JCOptionPersistenceDelegate());
        encoder.writeObject(opt);
        encoder.close();
    }Since this class does not fully comply to the JavaBeans conventions by not having a public no-argument constructor, I have create a class JCOptionPersistenceDelegate that extends the PersistenceDelegate. The implementation of the instantiate method is as follows:
      protected Expression instantiate(Object oldInstance, Encoder out) {
           Expression expression = new Expression(oldInstance, oldInstance.getClass(), "getOption", new Object[]{});
            return expression;
      }The problem is that the resulting XML file only contains the following lines:
        <java version="1.5.0_06" class="java.beans.XMLDecoder">
            <object class="JCOption" property="option"/>
        </java> so there is no trace of the property x.
    Thank you in advance for your answers.

    How about this:
    import java.beans.DefaultPersistenceDelegate;
    import java.beans.Encoder;
    import java.beans.Expression;
    import java.beans.Statement;
    import java.beans.XMLEncoder;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    public class JCOption {
        private int x = 1;
        private static JCOption option = new JCOption();
        private JCOption() {}
        public static JCOption getOption() { return option; }
        public int getX() { return x; }
        public void setX(int x) { this.x = x; }
        public static void main(String args[]) throws IOException {
          JCOption opt = JCOption.getOption();
          opt.setX(10);
          ByteArrayOutputStream os = new ByteArrayOutputStream();
          XMLEncoder encoder = new XMLEncoder( os );
          encoder.setPersistenceDelegate( opt.getClass(), new JCOptionPersistenceDelegate() );
          encoder.writeObject(opt);
          encoder.close();
          System.out.println( os.toString() );
    class JCOptionPersistenceDelegate extends DefaultPersistenceDelegate {
        protected Expression instantiate(Object oldInstance, Encoder out) {
            return new Expression(
                    oldInstance,
                    oldInstance.getClass(),
                    "getOption",
                    new Object[]{} );
        protected void initialize( Class<?> type, Object oldInstance, Object newInstance, Encoder out ) {
            super.initialize( type, oldInstance, newInstance, out );
            JCOption q = (JCOption)oldInstance;
            out.writeStatement( new Statement( oldInstance, "setX", new Object[] { q.getX() } ) );
    }   Output:
    <?xml version="1.0" encoding="UTF-8"?>
    <java version="1.5.0_06" class="java.beans.XMLDecoder">
    <object class="JCOption" property="option">
      <void property="x">
       <int>10</int>
      </void>
    </object>
    </java>

  • Transform a class that implements JPanel into a bean.

    I'd to create a bean, from a class that implements JPanel, that in fact is a custom component.
    How can I create a bean?
    I have absolutely no idea about beans.
    What can make beans for me?
    I know a lot about the theory of ejb, is this what I need?
    I'm quite confused, please make me see the light!!!!!
    Thanks.

    Hi Daniel!
    To answer your question short as possible:
    Java -Beans are reusable code - components,
    similar to VB Active -X components,
    which you can use when developing your own
    applications.
    Beans can have a graphic user interface, so you
    can use builder tools like JBuilder or Beanbox
    to show them graphically in a designer.
    You can modify them about their properties,
    mostly shown in a special property window of a
    builder tool.
    It's really not very hard to create your own beans,
    the only thing you have to do is to pack all the
    classes which make the bean into a jar file.
    Then you can import the bean with the builder
    and it will be shown.
    The jar manifest file needs to look like for example:
    Manifest-Version: 1.0
    Name: BeanClock.class
    Java-Bean: True
    All the properties are implemented by public property-get
    and property-set methods, in order to show them in the property window.
    Java is doing that by introspection.
    Hope, this makes it a little bit clearer for you!

  • Reflect the class that implements Runnable

    Hi,
    I am implementing the reflection of the class that implements Runnable. In order to start a new thread I am trying to invoke "start()" method ( which is obviously not defined my class ) and I therefore I am getting "java.lang.NoSuchMethodException".
    I am wondering is it possible at all to start a new thread on a reflected class?
    thanks in advance.
    {              Class refClass = Class.forName(className);
    String methodName = "start";
    Class[] types = new Class[1];
    types[0] = Class.forName("java.util.HashMap");
    Constructor cons = refClass.getConstructor(types);
    Object[] params = new Object[5];
    params[0] = new HashMap();
    Method libMethod = refClass.getMethod(methodName, null);
    libMethod.invoke(objType, null); }

    Well, if we knew what it meant to "start a thread on a class" we could probably figure out how to "start a thread on a reflected class". If we knew what a "reflected class" was, that is.
    In other words, it would help if you rephrased your question using standard terminology (and also explained why you want to do whatever it is you want to do).
    But let's guess for now: If you have an object which implements Runnable then you start a thread to run that object like this:
    Runnable r = // some object which implements Runnable
    new Thread(r).start();Not what you wanted? Go ahead and clarify then.

  • HELP?! a class that implements .....  : java.util.Vector

    My instructions say this:
    In the constructor, create the collection object (Since java.util.List is an interface, you will need to instantiate a class that implements this interface: java.util.Vector or java.util.LinkedList or java.util.ArrayList).
    I know, this IS a homework assignment - I am not sure how to go about this. I DO have code so far up to this point, can anyone help?
    import dLibrary.*;
    import java.awt.Color;
    * @author Rob
    * @version 8/18/03
    public class PhrasesII extends A3ButtonHandler
            private A3ButtonWindow win;
            private ATextField stringAcceptor;
            private ALabel listOstrings;
            private ALabel inputString;
            private ALabel status;
            private java.awt.List display;
            private java.util.List collection;
    public PhrasesII()
            win = new A3ButtonWindow(this);
            stringAcceptor= new ATextField (50,420,200,25);
            stringAcceptor.place(win);
            listOstrings = new ALabel(100, 10, 100, 380);
            listOstrings.setFontSize(10);
            listOstrings.setText("List of Strings:");
            listOstrings.place(win);
            inputString = new ALabel(50,400,200,25);
            inputString.setFontSize(10);
            inputString.setText("Input String:");
            inputString.place(win);
            display = new java.awt.List();
            display.setLocation(200, 100);
            display.setSize(200, 250);
            display.setBackground(Color.lightGray);
            win.add(display, 0);
            win.setLeftText("Save");
            win.setMidText("Display");
            win.setRightText("Discard");
            win.repaint();
      public void leftAction()
        public void midAction()
        public void rightAction()

    I am getting a " can't resolve symbol" when I do thisYou have to either import java.util.ArrayList or specify it fully, e.g., "new java.util.ArrayList()".
    Is that the line that is causing you problems? The error message should give the line number.
    my instructions also say I have to use "interface
    java.util.List when declaring your reference" so I am
    confused about using "= new ArrayList();"What they're saying is that you want code like this:
    private java.util.List frogs;    // this is the reference declaration
    //... later on...
    frogs = new java.util.ArrayList();  // this isn't a declarationWhat this means is that when you declare a field or variable, you should declare its type to be an interface.
    But when you actually instantiate a value for that variable, then you should use a concrete class that implements that interface. (You have to; interfaces can't be instantiated.)
    This is good programming style for reasons I don't have the space to explain here.

  • Serialize a value object that implements Comparator T

    Hi.
    I'm implementing a VO like this:
    public class RegionVO implements Serializable, Comparable<RegionVO>My problem is that i need that the class could be serialized completely.
    The VO will be transfered throught EJB's and by past experiences with EJB 2 projects (the actual project is developed with EJB 3) and running the project in clusters, the application crashes to use VO defined like that.
    I think that the problem is caused by implement Comparable too, this inteface isn't serializable and even if implement of Serializable interface, at least 1 method (compareTo(RegionVO o))not would serializable.
    My question is if that is true, how to solve to serialize the entire VO.
    Thanks.
    Edited by: terinlagos on Jul 24, 2008 2:48 PM

    terinlagos wrote:
    Well, the question was because if eventually could have the same problem when in the future the application run in a clusterized server. Actually in my pc has no problem.Well at least you are thinking that clustering will introduce problems you don't have currently.
    I suggest you start trying to cluster you application as early as possible, you undoubtedly will have allot of lessons to learn (I have never seen a cluster solution from an it-works-on-my-pc solution not run into unexpected problems)
    Note: you can run a "clustered" solution on a single PC just in multiple JVMs (which would be deployed to different machines in your final solution)
    You should make looking at this your top priority. IMHO.

  • Modifying a Class that implements Serializable

    I have a class LDAPUser
    import java.io.*;
    public class LDAPUser implements java.io.Serializable{
         private java.lang.String name;
         private java.lang.String userID;
         private java.lang.String associateNumber;
    public LDAPUser() {
         super();
    public boolean equals(Object o) {
         if (o == this)
         return true;
         if (!(o instanceof LDAPUser))
         return false;
         return (((LDAPUser)o).getAssociateNumber().equals(this.getAssociateNumber()));
    public java.lang.String getAssociateNumber() {
         if(associateNumber == null){
              return getUserID();
         return associateNumber;
    public java.lang.String getName() {
         return name;
    public java.lang.String getUserID() {
         return userID;
    public void setAssociateNumber(java.lang.String newAssociateNumber) {
         associateNumber = newAssociateNumber;
    public void setName(java.lang.String newName) {
         name = newName;
    public void setUserID(java.lang.String newUserID) {
         userID = newUserID;
    It works fine.
    I needed to add functionality to it. These were the modifications.
    private java.lang.String distinguishedName;
    private boolean validUser;
    public java.lang.String getDistinguishedName() {
         return distinguishedName;
    public boolean isValidUser() {
         return validUser;
    public void setDistinguishedName(java.lang.String newDistinguishedName) {
         distinguishedName = newDistinguishedName;
    public void setValidUser(boolean newValidUser) {
         validUser = newValidUser;
    I am using visual age for java and in the Test environment the changes work fine.
    When I promote the changes to our application server (websphere) the changes are not there. I get a method not found error and though trial and error have identified that the server is not actually using the class from the jar. I have removed any other occurences of the class from the server.
    My question is if I change a Serializable class how do I make those changes take affect (thorough better coding) and for right now, where is this "old instance" of my class coming from and how do I get rid of it.
    Thanks in Advance,
    Jason Grieve

    If the server is running than the class might be already loaded through the class loader, so it wont be load again.
    this unless you use hot deployment, which you have to figure how it is being handled in your srver.
    Doron

  • Question about methods in a class that implements Runnable

    I have a class that contains methods that are called by other classes. I wanted it to run in its own thread (to free up the SWT GUI thread because it appeared to be blocking the GUI thread). So, I had it implement Runnable, made a run method that just waits for the thread to be stopped:
    while (StopTheThread == false)
    try
    Thread.sleep(10);
    catch (InterruptedException e)
    //System.out.println("here");
    (the thread is started in the class constructor)
    I assumed that the other methods in this class would be running in the thread and would thus not block when called, but it appears the SWT GUI thread is still blocked. Is my assumption wrong?

    powerdroid wrote:
    Oh, excellent. Thank you for this explanation. So, if the run method calls any other method in the class, those are run in the new thread, but any time a method is called from another class, it runs on the calling class' thread. Correct?Yes.
    This will work fine, in that I can have the run method do all the necessary calling of the other methods, but how can I get return values back to the original (to know the results of the process run in the new thread)?Easy: use higher-level classes than thread. Specifically those found in java.util.concurrent:
    public class MyCallable implements Callable<Foo> {
      public Foo call() {
        return SomeClass.doExpensiveCalculation();
    ExecutorService executor = Executors.newFixedThreadPool();
    Future<Foo> future = executor.submit(new MyCallable());
    // do some other stuff
    Foo result = future.get(); // get will wait until MyCallable is finished or return the value immediately when it is already done.

  • Importing classes that implement jsp tags

              I was making a custom JSP tag library. The tag functionality was implemented in
              a class called, lets cay ClassA. I made the tld file and put it under the WEB-INF
              directory. The class which implemented the functionality was placed under WEB-INF/classes
              directory. I had the imported the tag library using the taglib directive. I was
              getting an error which said "cannot resolve symbol". But when I in the JSP file
              I imported the class file which implemented the taglib functionality the error
              vanished. Is it necessary to import the class files even if the taglib is imported.
              The documentation does not say so. Or is there some configuration I have to make.
              

    I think was a side effect of the .jsp changing redeploys the web app in 6.0.
              When the web app was redeployed your directory structure was reread and thus
              it found your .tld.
              Sam
              "bbaby" <[email protected]> wrote in message
              news:3b422db7$[email protected]..
              >
              > I was making a custom JSP tag library. The tag functionality was
              implemented in
              > a class called, lets cay ClassA. I made the tld file and put it under the
              WEB-INF
              > directory. The class which implemented the functionality was placed under
              WEB-INF/classes
              > directory. I had the imported the tag library using the taglib directive.
              I was
              > getting an error which said "cannot resolve symbol". But when I in the JSP
              file
              > I imported the class file which implemented the taglib functionality the
              error
              > vanished. Is it necessary to import the class files even if the taglib is
              imported.
              > The documentation does not say so. Or is there some configuration I have
              to make.
              >
              >
              

  • Example class that implements Serializable interface

    Dear,
    I have a class myData that I want to implement Serializable interface. class myData has only two fields: Integer iData1, String sData2.
    Could anybody shown me how my myData class should be?
    Thanks a lot!

    Hey, if you have yet to obtain a remote reference from the app server ...then we are into pandora's box. I lost three whole heads of hair getting up on JBoss when I first started. You want to check out the JBoss forums on the JBoss website, and the enterprise javabeans forum here. Search some posts and read the free JBoss manual.
    Unfortunately, there isn't a 'here, do this' solution to getting connected with JBoss. There are quite a few gotcha's. There are descriptors, descriptor syntax ...and this changes between releases so there seems to be alot of people saying 'here, do this' ...but you try and it doesn't work (wrong release). Here are some descriptors that I threw up recently for someone ...a place to start.
    http://forum.java.sun.com/thread.jsp?forum=13&thread=414432
    This drove me nuts until it all worked right. I was stuck for three weeks at one point ...ready to give up, but then I got it. Perservere ...its a nice container for learning in (its free!).
    I will try and watch for you.
    Oh, and put something in your head ...at least then you will keep your hair !
    :)

  • Implementing Comparable in an abstract class

    Hi all,
    I am making my first sortie with abstract classes. I have had a good look around, but would still appreciate some advice with the following problem.
    In my application I have several classes that have many things in common. I have concluded therefore, that if I create and then inherit from an abstract super class, I can reduce and improve my code. I created this abstract class:
    public abstract class YAbstractObject implements Comparable {
        public YAbstractObject(int projectId, YObject object, String objectName) {
            this.projectId = projectId; // Always the same parameters
            this.object = object;
            this.objectName = objectName;
        // This is abstract as it must always be present for sub classes but differant processing will take place
        public abstract void resolveObject();
        // These three methods will always be the same for all sub classes
        public String getName() {
            return objectName;
        public YObject getObject() {
            return object;
        public boolean isValid() {
            return isValid;
    // Overridden and always the same for all sub classes
        public String toString() {
            return objectName;
        // implemented abstract method
        public int compareTo(Object thatObject) {
            // Issue here! I would like something as follows:
            //  return this.getName().compareToIgnoreCase(thatObject.getName());
    // Variable decleration
        private int projectId;
        private YObject object;
        private String objectName;
        private boolean isValid;As I have commented in the compareTo() method, I would like it to be able to use the getName() method for comparison objects and compare them. But it does not like this, as it does not know that "thatObject" is of the same class as this object - I hope that made sense.
    in essence, I want to inherit this method for different classes and have it work with each.
    Is there a way to do this? Generics?
    Any observations, greatly appreciated,
    Steve

    You can use also generics (if applicable: java -version >= 1.5).
    public abstract class Test implements Comparable<Test> {
         String name;
         public Test(String name) {
              this.name = name;
         public String getName() {
              return name;
         public int compareTo(Test obj) {
              return this.getName().compareTo(obj.getName());
    public class Other extends Test {
         public Other(String name) {
              super(name);
    public class Tester extends Test {
         public Tester(String name) {
              super(name);
         public static void main(String[] args) {
              Test t = new Tester("t");
              Test a = new Tester("a");
              Test o = new Other("t");
              System.out.println(t.compareTo(a));
              System.out.println(t.compareTo(new Object())); //compile error
              System.out.println(t.compareTo(o));
    }Without the compile error line it will give the following result:
    19
    0

  • BUG:generate accessors not doing anything on abstract class

    I can't get a source file (abstract class) to generate accessors. I am using 10.1.3.0.0 production release. Concrete classes generate accessors fine.
    Here is how to reproduce the problem:
    Create an interface MyInterface with getMyThing() and setMyThing(String thing)
    Create an abstract class that implements MyInterface
    add a property and select generate accessor either from the source or from the menu "source"
    nothing happens
    remove the abstract keyword and the interface implementation -- generate accessors work fine
    Message was edited by:
    jgammon

    actually -- jdev version is 10.1.3.0.4 (SU1) build is JDEVADF_10.1.3_NT_060125.0900.3673

  • I want to make sure about abstract classes issue

    Hello,
    I have an interface with two methods.
    interface call{
    void trial (int p);
    void show();
    And an abstract class that implements that interface with overriding only one method of the two.
    abstract class client implements call {
    public void trial(int num) { System.out.println(num);}
    In the main method, I wanted to instantiate the implementing class in order to make use of the one method it overrides, but I received an error that the class as abstract, cannot be instantiated.
    class test{
    public static void main(String args[]) {
    //creating object reference to the implementing class
    client c = new client(); //the error is here
    c.trial(5);
    //creating an interface reference
    call m = new client(); //also doesn't work
    m.trial(5);
    So does I understand from this that if a class does not provide full implementation of an interface (i.e. abstract class), it cannot be used inside my program?
    Thanks!

    Please use code tags (see CODE button above posting box). Also, please use standard Java conventions of using a capital letter to start a class name.
    You are getting that error message because you didn't define show, and the interface requires it. You have to extend the Client abstract class to define show.
    You can make an anonymous class that defines show:
    Call m = new Client() {
       public void show() {
          System.out.println("Do something.");
    m.trial(5);Or, you can make a non-anonymous class that defines show:
    class MyClient extends Client {
       public void show() {
    }In this example, "show" doesn't actually do anything, but it does satisfy the interface. You can put the same "show" as I put in my anonymous class, or you can do whatever you want in "show".
    Then, in your "main", you'd have:
    MyClient client = new MyClient();
    client.trial(5);
    //or
    Call anotherClient = new MyClient();
    anotherClient.trial(6);
    //or
    Client yetAnotherClient = new MyClient();
    yetAnotherClient.trial(7);

Maybe you are looking for