Abstract class confusion

I am writing a J2ME application, and I want to write a Record management system (RMS) that I can use in other J2ME programs. I have a Record class that RMS classes need to know about. The idea is that the Record class is abstract, and the implementation is defined by a subclass - depending on what the application needs to store. Any Record must provide the following:
1) A constructor which takes a single byte[] parameter, which is the data read in from the RecordStore by the RMS. The implementation depends on what information is stored in this type of Record - it might be a String, series of ints, etc...
2) A method getStorageFormat() which returns a btye[] representing the data to be stored in the RecordStore. Again, this is dependent on the application.
I think that I have to use an abstract class here, so I have written an abstract class called Record - here's what it looks like:
public abstract class Record {
     public Record(byte[] bytes) { }; //Should this be an empty constructor?
     public abstract byte[] getStorageFormat();
}My problem is that I can't define a subclass of Record that works! Here's an example:
public class MyRecord extends Record {
       String data1, data2, data3; //Some data that is stored in this record
       public MyRecord(byte[] bytes) {
              String data = new String(bytes);
              // do some processing to extract the data...
       public byte[] getStorageFormat() {
              String sep = ","; //A seperator
              String tmp = data1 + sep + data2 + sep + data3; //put all the data together with
              return tmp.getBytes();
}}I get an error in Eclipse with the MyRecord constructor that says:" The implicit super constructor Record() is undefined. Must explicity invoke another constructor". I tried super() but I get the same error. Can anyone please tell me what I am doing wrong? It seems to me that I am misunderstanding something about how abstract classes work.

Because you defined a ctor that takes args, the implicit one that takes no args--super()--is no longer implicitly supplied. You have to either put a no-arg ctor into the parent class, or call the one that you already have.
public Record(byte[] bytes) { }; //Should this be an empty constructor?
public abstract byte[] getStorageFormat();
}No. You don't want a ctor that takes args and does nothing. If you're taking that arg, then you should use it to initialize the state of the object.
Here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.
1) Every class has at least one ctor.
1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a
public MyClass() {...}
if you want one.
1.3) Constructors are not inherited.
2) The first statement in the body of any ctor is either a call to a superclass ctor
super(...)
or a call to another ctor of this class
this(...)
2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor
super()
as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

Similar Messages

  • What is the diff b/w Abstract class and an interface ?

    Hey
    I am always confused as with this issue : diff b/w Abstract class and an interface ?
    Which is more powerful in what situation.
    Regards
    Vinay

    Hi, Don't worry I am teach you
    Abstract class and Interface
    An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
    Edited by SASIKUMARA
    SIT INNOVATIONS- Chennai
    Message was edited by:
    sasikumara
    Message was edited by:
    sasikumara

  • Calling a method from an abstract class in a seperate class

    I am trying to call the getID() method from the Chat class in the getIDs() method in the Outputter class. I would usually instantiate with a normal class but I know you cant instantiate the method when using abstract classes. I've been going over and over my theory and have just become more confused??
    Package Chatroom
    public abstract class Chat
       private String id;
       public String getID()
          return id;
       protected void setId(String s)
          id = s;
       public abstract void sendMessageToUser(String msg);
    Package Chatroom
    public class Outputter
    public String[] getIDs()
         // This is where I get confused. I know you can't instantiate the object like:
            Chat users=new Chat();
            users.getID();
    I have the two classes in the package and you need to that to be able to use a class' methods in another class.
    Please help me :(                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    I have just looked over my program and realised my class names are not the most discriptive, so I have renamed them to give you a clearer picture.
    package Chatroom
    public abstract class Chatter
    private String id;
    public String getID()
    return id;
    protected void setId(String s)
    id = s;
    I am trying to slowly build a chatroom on my own. The Chatter class is a class that will be used to represent a single logged in user and the user is given an ID when he logs in through the setId and getID() methods.
    package Chatroom;
    import java.util.Vector;
    public class Broadcaster
    private Vector<Chatter> chatters = new Vector<Chatter>();
    public String[] getIDs()
    // code here
    The Broadcaster class will keep a list of all logged-in users keeps a list of all the chats representing logged-in users, which it stores in a Vector.I am trying to use the getIDs() method to return an array of Strings comprising the IDs of all logged-in users, which is why im trying to use the getID() method from the Chat class.
    I apologise if I come across as clueless, it's just I have been going through books for about 4 hours now and I have just totally lossed all my bearings

  • When we will go for an abstract class and when we will go for an interface?

    it's always some what confusing to choose an abstract class and an interface,can anybody post a suitable answer for this.

    jwenting wrote:
    with experience and the insight it brings, you will know which to use when.
    Without it, it can't be explained.
    More often than not there's no X OR Y anyway.It's fortunate that there are posters here who possess the insight and experience necessary to explain this. The principal differences between an abstract class and an interface are,
    1. An abstract class can carry implementation, whereas an interface cannot.
    2. An abstract class is singly inherited, wheras an interface is multiply inherited.
    So use an abstract class when the implementation it can carry outweights the fact that it cannot be multiply inherited That's the gist of it.
    The inheritance relationship where this happens is when the supertype is a general concept of which all potential subtypes are special cases. This is called a specialization (or sometimes a generalization) relationship. For example Apple and Banana are Fruit. Or Car and Bike are Vechicle. The Fruit and Vechicle supertypes are general concepts of which their subtypes are special cases. In this case make Fruit and Vechicle abstract classes because the subtypes will benefit from a shared implementation.
    If you don't have a clearcut specialization/generalization relationship make the supertype an interface. An example could be the Comparable supertype. The potential subtypes aren't supposed to be specializations of the Comparable concept, they're suppose to become Comparable (and make this property an integral part of their being). This is not a specialization/generalization relationship. Instead the supertype is intended to add character to the subtypes. The subtypes are unlikely to benefit from an inherited implementation. So make Comparable an interface.

  • Why abstract classes

    Pals,
    Abstract classes help us in abstracting common code. The same can be achieved by using a plain java class with static methods and extending them. What extra does this abstract keyword provides

    Thanks fro the reply , but still im confused ,
    partial implementations can also be done using the
    Plain class (say class A)and having a non static
    method in it (say methA(). Another class can can
    extend this class A and use / override this(methA())
    partial implementation of class A. I googled but
    couldnt find an explaining answerIn the JDK that you downloaded is src.zip. Unzip it. Look at the source code for some of the abstract classes and the concrete classes that extend them.
    For example, in List implementations, how you implement the add method is very much dependent on how the list is implemented. It's very different for a LinkedList vs. an ArrayList. It's highly dependent on the data structure that holds the list's elments. There's no reasonable way to implement it in the base class, so it's abstract.
    The addAll method, on the other hand, can be implemented completely in terms of other methods and is not dependent on the implementation details. You simply iterate over the collection that's passed in as an arg, and for each of its elements, you call this list's add() method. So addAll can be implemented in the base class--all subclasses can use the same implementation.

  • Final methods in abstract classes?

    Hi, why is it possible to define a final method in an abstract class? The theory behind a final method doesn't say that a final method couldn't be overridden?
    Marco

    So it's formally correct but it doesn't have any
    sense, does it?You sound very confused. A final method in an
    abstract class has just the same semantics and
    makes just as much sense as in a non-abstract
    class.
    The semantics of a final method is simply that
    it cannot be overridden in subclassed. Both
    abstract and non-abstract classes can be
    subclasses. So why do you think there should be any
    difference?Actually i was confused now it's clear. I was too binded to the concept that the extending class SHOULD(not for a formal reason, but for a 'design' one) write the implementation of the methods defined in the abstract class. Now i see that, actually, by defining a final method in an abstract class we are defining our design as implemented and clients(i.e. subclasses) can only use it.
    Thank you,
    Marco

  • Problems with abstract classes

    I'm reading Java Wireless Blueprints and i'm confused with the functionality of abstract classes, especially in the next section:
    public byte[] getPoster() throws ApplicationException {
    if (poster == null) {
    try {
    poster =
    ModelObjectLoader.getInstance().getMoviePoster(primaryKey);
    } catch (ModelException me) {
    throw new ApplicationException();
    return poster;
    This class invoque to the ModelObjectLoader class that is abstract and after invoque getInstance().getMoviePoster(primaryKey); method. The source code of the class is:
    public abstract class ModelObjectLoader {
    private static ModelObjectLoader instance = null;
    protected ModelObjectLoader() {
    instance = this;
    return;
    public static ModelObjectLoader getInstance() {
    return instance;
    public abstract TheaterSchedule getTheaterSchedule(Theater theater)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(String movieKey)
    throws ModelException, ApplicationException;
    public abstract Movie getMovie(Movie movie)
    throws ModelException, ApplicationException;
    public abstract byte[] getMoviePoster(String movieKey)
    throws ModelException, ApplicationException;
    public abstract int[][] getMovieShowTimes(String theaterKey, String movieKey)
    throws ModelException, ApplicationException;
    public abstract SeatingPlan getSeatingPlan(String theaterKey,
    String movieKey,
    int[] showTime) throws ModelException,
    ApplicationException;
    I don�t find where is the implementation of the getMoviePoster(primaryKey) method.
    Can you help me to understand.
    Thanks

    public abstract byte[] getMoviePoster(String movieKey)It's an abstract method, which means that any concrete class that extends ModelObjectLoader must implement the method. If you really need to know (you might not), then call getInstance() and output the result of getClass().getName() on that object. That will tell you its type, and then you can go look at the source.

  • Abstract class methods

    I'm confused. Is this true or false.
    The great thing about polymorphism is that you can call one method. If the subclass inherited that method, it will be customized and perform a different duty. That way, the action it performs will depend on 1>whether or not it's a sub or super class and also 2>if the method was overridden if it was a subclass.
    Now, my confusion. If an object reference is to a Super-abstract-class... how do the method calls and properties go?? well let me let you answer for me. Thanks so much in advance for this clarification.

    Yes. You are - pretty much.
    The abstract class, as such, can never be instantiated. BUT a class derived from the superclass IS an instance of the superclass.
    Silly example:
    abstract public class Animal {
       public Animal() {
       public abstract int getNumberOfLegs();
    }That's our animal class, and we know that anything that's an animal has a number of legs - but we can't just create a "generic" animal.
    public class Cat extends Animal {
       public Cat() {
          super();
       public int getNumberOfLegs() {
          return legCount;
       public void maim(int legsToRemove) {
          legCount -= legsToRemove;
          if(legCount < 0 ) legCount = 0;
       private int legCount = 4;
    }A Cat is a specific type of animal, so we can find out how many legs it has (usually 4). Note again that a cat IS an animal, so Cat IS an instance of Animal.
    Java even provides a special operator to test this:
    Cat cat = new Cat();
    System.out.println("A cat is a cat: " + (cat instanceof Cat));
    System.out.println("A cat is an animal: " + (cat instanceof Animal));The term used to describe the "Guarantee" that a subclass of an abstract class (or an implementation of an interface) is usually and technically a "contract", but I prefer to think of it as a "Promise" since you can break the promise by messing with the bytecode - at which point the JVM will spot the lie and complain !
    D.

  • Abstract class, a question

    i have an abstract class called shape with default constructor (double y1, double y2);
    with an abstract method area.
    now i have a circle class which extends it, but i want its constructor to have ONE radius (as its pi radius*radius)
    at the moment this is how my circle looks like, and as you can see that there is really no need for second radius how can i modify circle class without modifying shape class?
    class circle extends Shape{
    circle(double radius, double radius1) {
         super(radius, radius);
    double area() {
    return (3.14*x1*x1);
    }

    the answer from the test class in above case will be
    0!Yes, because 3.14 * 0 * 0 is 0.
    but if i change the x3 above to x1, it would work, You honestly don't see why? It's staring you right in the face. What does area() use? How does that field get set?
    the
    reason i decided to use x3 is so that ppl dont get
    confuse! Here's what's confusing:
    * field names x1, x2, x3. What do those mean? They sound like 3 x coordinates.
    * two fields that are used by certain subclasses, but not others, and a third field that's used only by the subclasses that don't use the first two.
    * that third field meaning "the single value that applies to what both of the other two fields mean" instead of just setting both fields to the same value.
    * having any of those fields in there at all in the first place when they're not used by the abstract class and not used consistently by subclasses.
    but shouldnt it work because i have done the
    same thing i did to x1 and x2??

  • Abstract Classes & Interface Classes

    Dear members of the Sun Community
    My studies are progressing and just 1 period ago we started doing Object-Orinted Programming in Java and I must say I'm quite fond of it. It's become quite clear that OOP is an important aspect of Programming and just can't be missed. We've learned about Inheritance, Polymorfism, Mutators, Inspectors, Uses-Relationships and everything else however now I've come to the point where I got a problem:
    Up until now we have been using normal classes to work with in which you could create objects and in your main program create objects from that class however. We've just learned about Abstract and Interface classes. As far as I'm concerned I'm quite confused with both of them.
    If I am not mistaken (please correct me if I'm wrong) Abstract classes are classes from which you cannot create an object but is only used to make a subclass inherit everything from this superclass.
    I am not quite sure what Interface classes are as they just plain confuse me. Would anyone be so kind to maybe explain what all of this is ?
    Thanks a whole bunch
    Herazio

    Funny enough that already solved the question !
    Thank you so much for the quick reply ^^
    Herazio

  • Abstract class reference itself

    How do I reference an abstract class to itself.
    public abstract class SomeClass {
       public static SomeType SomeMethod(){
             SomeClass mine = new SomeClass();
       }It gives me an error saying it can not instantiate the class.

    Possible source of confusion: you can declare a variable of type abstract class and assign it an object of a derived class that fully implements the abstract class. For instance:
    abstract class SomeClass
         public static void SomeMethod(){}
         public abstract void greeting();
    class AnotherClass extends SomeClass
         public void greeting()
              System.out.println("hello");
    public class DemoAbstractClasses
         public static void main(String args[])
              SomeClass A = new AnotherClass(); // A's type is an abstract class
              A.greeting();  //polymorphism
    }

  • Abstract class Calendar

    I'm very confused about the abstract class Calendar, I ever thought that an abstract class can't instantiate objects. But this class do. thanks to the method Calendar.getInstance(); this is my headache. How is it possible?

    I'm very confused about the abstract class Calendar,
    I ever thought that an abstract class can't
    instantiate objects. But this class do. thanks to the
    method Calendar.getInstance(); this is my headache.
    How is it possible?It returns an instance of a class that EXTENDS Calendar. Unless you are in Thailand it returns a GregorianCalendar.

  • What is the benefit of abstract classes?

    I am little bit confuse regarding the benefits of the abstract classes. Can anybody helps me in this regard. I just want to know when and what situation we may decide that particular class needs an abstract method.
    Thanx

    I am little bit confuse regarding the benefits of the
    abstract classes. Can anybody helps me in this
    regard. I just want to know when and what situation
    we may decide that particular class needs an abstract
    method.Sorry if I sound weary of this question, but it is asked about 3-4 times a week. Rather than have us go through this tired exercise again, please search the forum for previous threads on this subject. You'll find about a gazillion. In fact, it's often a good idea to search the forum before asking a question as very often it has been asked and answered before.

  • Documentation formats for interfaces, classes, abstract classes

    I am writing docs and want to make sure it conforms to best practices. Here is what I am doing:
    interfaces = [italics, not bold]
    classes = [not italics, bold]
    abstract classes = [italics, bold]
    I am most unsure of abstract classes?
    That is important to me, so please help me get this straight. thanks.

    Everybody knows that interfaces are blue, classes are red, and abstract classes use jumpy text.
    (that was a joke by the way)
    To my mind, using bold for abstract classes would be misleading. Just on an intuitive level, bold seems more concrete. But that's just me. I think the best thing to do is just to decorate the names with "<<interface>>" or "<<abstract>>" so there's no confusion.

  • Difference between abstract class and interface

    Hi everyone,
    CAn anyone explain why the following happen????
    Abstract class can have a constructor, Interface cannot.
    Abstract class can have static methods, Interface cannot.

    What are the advantages of defining constant
    variables in Interfaces?Not many.
    Effective Java - Joshua Bloch, Chapter 4, Item #17: Use interfaces only to define types.
    The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.
    In summary, interfaces should only be used to define types. They should not be used to export constants.

Maybe you are looking for

  • Has anyone figured out how to limit the number of emails displayed in the mail app?

    There used to be a setting in Mail, Calendar, Contacts that would let you set the number, starting with 50 emails.  I can't find this setting in iOS 7.

  • Check DB Failure in ECC 6.0

    Dear All, Check database consistency failed in DB13 for the below system. We got the same error in DEV, QAS, PRD. SAP: Ecc6.0 - Non Unicode OS : Windows 2003 server R2 SP2 DB : MSSQL 2005 (4035) error =================================================

  • Passing "-t" option to link-editor via CC

    Hi! Here is the simple task. we have some source file which is compiling with simple command: CC ./some_simple_file.C -lsome_lib -lanother_libCompilation process succed but we have the warning message: ld: warning: symbol ‘array’ has differing sizes:

  • Java object as input in XSL-FO processor?

    I want to generate XSL-FO document from XSLT document and from an object in Java (for example ArrayList). Can you tell me if there is a library with this functionality? I want to omit generating XML from ArrayList. thanks steensh

  • Netflix plug in error after lion install

    What is the fix for Netflix plug in error after lion install?