Abstract class method polymorphically using constructors?

how can i have a method defined in an abstract superclass call a constructor of the actual class running the method?
abstract class A {
public List getMultple() {
List l = new ArrayList();
for (short i=0;i<4;i++) {
l.add(this());//<obviously this breaks
return l
or something like that. A won't run this method, but its children will...and they can call their constructors, but what do i put here to do that?
i've tried a call back. an abstract method getOne() in the superclass forces each child to define that method and in each of those i return the results of a constructor. that works fine.
the problem is i want to abstract this method out of each of these children classes cause its the exact same in each one, just using a different constructor to get multiple of each in a list. so if i use this callback method, then i am not saving the number of methods in each class, so why bother at all?
any ideas?

I still say you are coming at it from the wrong angle. A super class is not the way to go. What you are doing sounds like something very similar to something I did not too long ago.
My requirement was that I had tab delimited text files filed with data that I had to parse. Each line would be used to instantiate one object, so a particular file could be used to instantiate, for example, a thousand objects of the same class. There were different types of files corresponding to different classes to instantiate instances of.
Here is the design I ended up using.
An object of class DataTextFileReader is instantiated to parse the text file and generate objects. It includes code for going line by line, handling bad lines and generating objects and reports. The constructor:
public DataTextFileReader(File inputFile, LineParser<T> theLineParser)LineParser is an interface with one method:
public T read(String line);When you call a load() method of the DataTextFileReader, it does its thing with the aid of the LineParser's read method, to which each line is passed, and stores the generated objects in an ArrayList. This can be returned by using another method. There are other methods for getting the reports, etc.
Obviously, the LineParser chosen needs to have code appropriate for parsing the lines in question, so you have to choose and instantiate the right one.
I find this design to work well. I arrived at it after spending hours giving myself headaches trying to come up with a design where there was a superclass roughly equivalent to the DataTextFileReader mentioned above, and classes extending this that fulfilled the duty of the LineParsers mentioned above... rather like what you are trying to do now.
I did not care for the solution at first because it did not give me the "Ah, I am clever!" sensation I was expecting when I finally cracked the problem using inheritance, but I quickly came to think that it was much better OOD anyway.
The LineParsers mentioned above are essentially embodiments of the Factory pattern, and I would recommend you do something similar in your case. Obviously your "constructors" all have to be different, so you should make a separate class for each of those. Then you can put the code that performs the query and loops to create loads of objects in another class called something like DatabaseDepopulator, using appropriate generics as in my example. Really it is the same problem, now that I look at it.
This will also result in better separation of concepts, if you ask me. Why should the class constructor know how to parse a database result query, much less perform the query? It has nothing to do with databases (I presume). That is the job of an interpreter object.
As a final note, remember... 95% of the time you feel like the language won't let you do what you want, it is because you shouldn't anyway.
Drake

Similar Messages

  • Abstract Class and polymorphism - class diagram

    Hi,
    ]Im trying to draw a class diagram for my overall system but im not too sure how to deal with classes derived from abstract classes. I'll explain my problem using the classic shape inheritance senario...
    myClass has a member of type Shape, but when the program is running shape gets instantiated to a circle, square or triangle for example -
    Shape s = new circle();
    since they are shapes. But at no stage is the class Shape instantiated.
    I then call things like s.Area();
    On my class diagram should there be any lines going from myClass directly to circle or triangle, or should a line just be joining myClass to Shape class?
    BTW - is s.Area() polymorphism?
    Thanks,
    Conor.

    Sorry, my drawing did not display very well.
    If you have MyClass, and it has a class variable of type Shape, and the class is responsible for creating MyClass, use Composition on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it has a class variable of type Shape, and the class is created elsewhere, use Aggregation on your UML diagram to link Shape and MyClass.
    If you have MyClass, and it is used in method signatures, but it is not a class variable, use Depedency on your UML diagram to link Shape and MyClass. The arrow will point to Shape.
    Shape and instances of Circle, Triangle, Square, etc. will be linked using a Generalization on your UML diagram. The arrow will always point to Shape.
    Anything that is abstract (class, method, variable, etc.) should be italicized. Concrete items (same list) should be formatted normally.
    BTW, the distinction between Composition, Aggregation and Dependency will vary from project to project or class to class. It's a gray area. Just be consistent or follow whatever guidelines have been established.
    - Saish

  • What are abstract classes/methods and what are they for?

    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.

    raggy wrote:
    bastones_ wrote:
    Hi,
    I've just heard about abstract classes and methods and I'm just wondering what exactly they're used for, and why are they there for the Graphics class for example?
    Cheers.Hey bro, I'll try to solve your problemYou have to know two important concepts for this part. 1 is Abstract classes and the other is Interface classes. Depends on the nature of the project, you need to set certain level of standards and rules that the other developers must follow. This is where Abstract classes and Interface classes come into picture.
    Abstract classes are usually used on small time projects, where it can have code implementation like general classes and also declare Abstract methods (empty methods that require implementation from the sub-classes).Wrong, they are used equally among big and small projects alike.
    Here are the rules of an Abstract class and method:
    1. Abstract classes cannot be instantiatedRight.
    2. Abstract class can extend an abstract class and implement several interface classesRight, but the same is true for non-abstract classes, so nothing special here.
    3. Abstract class cannot extend a general class or an interfaceWrong. Abstract classes can extend non-abstract ones. Best example: Object is non-abstract. How would you write an abstract class that doesn't extend Object (directly or indirectly)?
    4. If a class contains Abstract method, the class has to be declared Abstract classRight.
    5. An Abstract class may or may not contain an Abstract methodRight, and an important point to realize. A class need not have abstract methods to be an abstract class, although usually it will.
    6. Abstract method should not have any code implementations, the sub-classes must override it (sub-class must give the code implementations). An abstract method must not have any implementation code code. It's more than a suggestion.
    7. If a sub-class of an Abstract class does not override the Abstract methods of its super-class, than the sub-class should be declared Abstract also.This follows from point 4.
    9. Abstract classes can only be declared with public and default access modifiers.That's the same for abstract and non-abstract classes.

  • Using Abstract Class Methods

    I just want to know that in how many ways can we use the non abstract methods of the class without extending the class(dont want to implement all abstract methods of the parent class).One way is that if the methods are static then we can use CLASSNAME.METHODNAME().Is their any other way of doing it

    none at all. not a single one. by definition, a non-static method has to be invoked on a particular instance of a class, and an abstract class cannot be instantiated. somebody is probably going to say you can do this:
    abstract class AbstractClass {
      abstract void minceAbout();
      void talkRubbish() {
         // do stuff
    new AbstractClass() {
        void minceAbout() {}
    }.talkRubbish();but that is extending the AbstractClass, no matter what their argument. why d'you ask, anyway? why not implement the methods? sounds like a design smell

  • 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/ method calls

    Hi, in an
    abstract class Report
    private int mat
    private string add
    private int mat
    private double creduced = 0.125;
    private double sreduced = 0.25;
    public Property(String location, int material)
    add = location;
    mat = material;
    public double getActualPrice()
    double base = getPrice();
    double money = base;
    if (mat == 1)
    money -= base * creduced;
    return money;
    etc and two abstract classes called getPrice() , and getInsurance()- which i have both coded in the extended class
    in a class called "class Info extends Report" I want to use the getActualPrice() method since it will anyway cause of inheritence but i want to add a new if line to it. How do I do this and code it in the extended class?
    Can i super call the instance variables and local variables ? I have tried super calls on the instance variables but since none of them are included in any of the constructors it wont work.

    public double getActualPrice()
    double actual=super.getActuelPrice();
    if ( something )
       actual=dosomethingwith(actual){
    return actual;
    }

  • Abstract class method returning unknown class

    Hi
    I have created an abstract class having one of the method returning an object of a class which is not present at the compiletime. surprisingly the compiler didn't check the availability of the returning class at compilation time. it gave exception of classnotfound when I tried to rum it.
    is there any explanation of it??

    Thanks for the replay. I got the reason.
    actually evenif I did not compile to class file, but I have kept my java file in the same directory. while compiling the abstract class the compiler automatically compiled the reffered class and generated the required class file.
    I got the error when I moved the java file to another dir
    the code is like
    <code>
    abstract class AbstractTest{
         CompleteClass method1(){
              System.out.println("inside method1 of abstract class");
              return new CompleteClass();
         ExtraClass method2(){
                   System.out.println("inside method2 of abstract class");
                   return new ExtraClass(); // this class was not compiled before
         } // only java file is there in the dir
         abstract void demoMethod();
    </code>

  • Method signature (Chapter : Abstract class and Polymorphism)

    Hi all,
    I found some quaint thing about signature method. It's said: "A child class may define additional methods with signatures different from the parent's method." but
    "It is an error if a child defines a method with the same signature as a parent method, but with a different return type."
    The thing is: return type is not belong to method's signature !!!
    Can someone explain this point?
    Thanks and have a nice day ( 11:00 am in Germany)
    H.A

    "It is an error if a child defines a method with the
    same signature as a parent method, but with a
    different return type."
    The thing is: return type is not belong to method's
    signature !!!
    Can someone explain this point?Yes.
    Even though return type isn't part of the "signature" (as the JLS defines "signature"), the JLS requires that child methods with the same signature as parent classes have the same return type.
    Think about it for a minute: Return type isn't part of the signature, but it is part of the contract. If Parent has public Whatsit foo() then it's promising that every instance of Parent, AND every instance of any Child that is a subclass of Parent (since a Child also IS A Parent), will have that method, and callers of that method will receive a Whatsit as a return value.
    If I try to override it in Child with public Doobley foo() then a call might try to do this: Parent parent = factory.createParent(); // happens to return a Child, which is allowed, because a Child is a Parent
    Whatsit w = parent.foo(); // OH NO! We got bad a Doobley instead of a Watsit! See the problem?
    Now, it turns out that 1.5 adds covariant return types, which allows a child method to return a subtype of what the parent returns. So the above would work IFF Doobley is a subclass or subinterface of Whatsis, or is a class that implements Whatsis. This works because the child is still keeping the parent's contract. He's just actually promising a bit more than what the parent promises.

  • Abstract Classes vs. Protected Constructors

    I thought I'd like to pose a more language philosophical question. (I sure miss Advanced Language Topics)
    Question: suppose one has a class which must be subclassed solely for runtime type identification (RTTI), i.e. the class is fully implemented, and even all of its methods are final.
    It seems to me the JLS offers two options:
    &nbsp&nbsp&nbsp&nbsp 1. Make the class abstract. (even though it has no abstract methods)
    &nbsp&nbsp&nbsp&nbsp 2. Make the constructor of the class protected.
    These approaches seem equivalent, however I am curious if anyone has reasons to prefer one approach over another.
    I suppose the exceptionally paranoid might even advocate using both! :-)
    Thanks for your participation, or at least reading.
    [url https://cajo.dev.java.net/index.html]-John
    PS There are Dukes available; if you have yet another interesting approach!

    how about:class Measure {
         public static final int FLUID_MEASURE     = 1;
         public static final int VOLUME_MEASURE     = 2;
          * Only way to get these things.
         public Measure createNew(int type){
              switch(type){
                   case FLUID_MEASURE:
                        return new FluidMeasure();
                   default:
                        throw new IllegalArgumentException("");
          * No instances or outside subclassing
          * allowed.
         private Measure(){}
          * Private so it can't be extended.
         private class FluidMeasure extends Measure { }
    } it directly prevents anyone from doing anything with the class ... you
    are in complete control of what subclasses are allowed ... :)

  • Java abstract classes and methods

    Can anyone please tell me any real time example of abstract classes and methods.
    I want to know its real use. If anyone have ever used it for some purpose while programming please do tell me.

    Ashu_Web wrote:
    No please.. I just want to know if you have used it while programming. Like "an abstract class can be used to put all the common method names in it without having to write actual implementation code."That would describe an Interface better than an abstract class. Abstract classes usually have at least some implementation.
    I want to know its usage in programming, not just a definition. I guess you understand what I am looking for.Yes, and I gave you one: java.util.AbstractList. It can be found inside the src.zip in your JDK directory and it is a pretty good example for an abstract class that provides some implementation and defines exactly what is necessary to make a full List implementation.

  • What is the advantage of abstract class and method???

    hi,
    * Why a class is declared as abstract???
    * What is the use of declaring a class as abstract???
    * At what situation abstract class will be used???Thanks
    JavaImran

    To save you from the wrath of the Java experts on this forum, allow me as a relatively new Java user to advise you: do NOT post homework problems here; you're just going to get told to go google the answer. Which would be a good move on your part. Especially since I found the answer to your questions by googling them myself.

  • Abstract Class & Interfaces

    Can anyone please tell me as to why we need both an abstract class & an interface? I was asked in an interview as to why we need 2 separate concepts when we can get the similar functionality of an interface by using an abstract class. I had just sited their differences like:
    1) An abstract class can have both abstract & normal methods & that we can specify different access specifiers for its class members.
    2) ABAP does not support Multiple inheritance but that we could simulate the same using interfaces concept in ABAP.
    But he wasnt satisfied with the answer. I guess he was expecting something from a practical point of view. I did try searching the old threads but there wasnt anything similar to this. Anyone please explain by citing a scenario as to why we would need 2 separate concepts & not just one .
    Thanks in advance

    Hi
    Abstract classes
    Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract) subclasses, for example to define a uniform interface.
    Classes with at least one abstract method are themselves abstract.
    Static methods and constructors cannot be abstract.
    You can specify the class of the instance to be created explicitly: CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>.
    Abstarct classes themselves can’t be instantiated ( althrough their subclasses can)
    Reference to abstract classes can refer to instance of subclass
    Abstract (instance) methods are difined in the class , but not implemented
    They must be redefined in subclasses
    CLASS LC1 DEFINAITION ABSTARCT
    PUBLIC SECTION
    METHODS ESTIMATE ABSTARCT IMPORTING…
    ENDCLASS.
    <b>Interfaces</b>
    Interfaces only describe the external point of contact of a class (protocols), they do not contain any implementation.
    Interfaces are usually defined by a user. The user describes in the interface which services (technical and semantic) it needs in order to carry out a task.
    The user never actually knows the providers of these services, but communicates with them through the interface.
    In this way the user is protected from actual implementations and can work in the same way with different classes/objects, as long as they provide the services required. This is known as polymorphism with interfaces.

  • Diffrence between a Interface and a abstract class?

    Hi OO ABAP Gurus
    Please clear below point to me.
    Diffrence between a Interface and a abstract class?
    Many thanks
    Sandeep Sharma..

    Hi
    Abstract classes
    Abstract classes are normally used as an incomplete blueprint for concrete (that is, non-abstract) subclasses, for example to define a uniform interface.
    Classes with at least one abstract method are themselves abstract.
    Static methods and constructors cannot be abstract.
    You can specify the class of the instance to be created explicitly: CREATE OBJECT <RefToAbstractClass> TYPE <NonAbstractSubclassName>.
    Abstarct classes themselves can’t be instantiated ( althrough their subclasses can)
    Reference to abstract classes can refer to instance of subclass
    Abstract (instance) methods are difined in the class , but not implemented
    They must be redefined in subclasses
    CLASS LC1 DEFINAITION ABSTARCT
    PUBLIC SECTION
    METHODS ESTIMATE ABSTARCT IMPORTING…
    ENDCLASS.
    Interfaces
    Interfaces only describe the external point of contact of a class (protocols), they do not contain any implementation.
    Interfaces are usually defined by a user. The user describes in the interface which services (technical and semantic) it needs in order to carry out a task.
    The user never actually knows the providers of these services, but communicates with them through the interface.
    In this way the user is protected from actual implementations and can work in the same way with different classes/objects, as long as they provide the services required. This is known as polymorphism with interfaces.
    Interfaces features
    INTERFACE I_COUNTER.
    METHODS: SET_COUNTER IMPORTING VALUE(SET_VALUE) TYPE I,           INCREMENT_COUNTER, ENDINTERFACE.
    CLASS C_COUNTER1 DEFINITION.   PUBLIC SECTION.
        INTERFACES I_COUNTER.
      PRIVATE SECTION.
        DATA COUNT TYPE I.
    ENDCLASS.
    CLASS C_COUNTER1 IMPLEMENTATION.
      METHOD I_COUNTER~SET_COUNTER.
        COUNT = SET_VALUE.
      ENDMETHOD.
      METHOD I_COUNTER~INCREMENT_COUNTER.
        ADD 1 TO COUNT.
      ENDMETHOD.
    ENDCLASS.
    Refer
    https://forums.sdn.sap.com/click.jspa?searchID=10535251&messageID=2902116
    Regards
    Kiran

  • Static Classes/Methods vs Objects/Instance Classes/Methods?

    Hi,
    I am reading "Official ABAP Programming Guidelines" book. And I saw the rule:
    Rule 5.3: Do Not Use Static Classes
    Preferably use objects instead of static classes. If you don't want to have a multiple instantiation, you can use singletons.
    I needed to create a global class and some methods under that. And there is no any object-oriented design idea exists. Instead of creating a function group/modules, I have decided to create a global class (even is a abstract class) and some static methods.So I directly use these static methods by using zcl_class=>method().
    But the rule above says "Don't use static classes/methods, always use instance methods if even there is no object-oriented design".
    The book listed several reasons, one for example
    1-) Static classes are implicitly loaded first time they are used, and the corresponding static constructor -of available- is executed. They remain in the memory as long as the current internal session exists. Therefore, if you use static classes, you cannot actually control the time of initialization and have no option to release the memory.
    So if I use a static class/method in a subroutine, it will be loaded into memory and it will stay in the memory till I close the program.
    But if I use instance class/method, I can CREATE OBJECT lo_object TYPE REF TO zcl_class then use method lo_object->method(), then I can FREE  lo_object to delete from the memory. Is my understanding correct?
    Any idea? What do you prefer Static Class OR Object/Instance Class?
    Thanks in advance.
    Tuncay

    @Naimesh Patel
    So you recommend to use instance class/methods even though method logic is just self-executable. Right?
    <h3>Example:</h3>
    <h4>Instance option</h4>
    CLASS zcl_class DEFINITION.
      METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    <h4>Static option</h4>
    CLASS zcl_class DEFINITION.
      CLASS-METHODS add_1 IMPORTING i_input type i EXPORTING e_output type i.
      CLASS-METHODS subtract_1 IMPORTING i_input type i EXPORTING e_output type i.
    ENDCLASS
    CLASS zcl_class IMPLEMENTATION.
      METHOD add_1.
        e_output = i_input + 1.
      ENDMETHOD.
      METHOD subtract_1.
        e_output = i_input - 1.
      ENDMETHOD.
    ENDCLASS
    CREATE OBJECT lo_object.
    lo_object->add_1(
    zcl_class=>add_1(
      exporting i_input = 1
      importing e_output = lv_output ).
    lo_object->subtract_1(
    zcl_class=>subtract_1(
      exporting i_input = 2
      importing e_output = lv_output2 ).
    So which option is best? Pros and Cons?

  • Abstract class and RMI

    Hi!
    I have a desgin where I have an abstract class that in its constructor registers itself in a registry and define three abstract methods. Then I have a class that extends the abstract class and implements the three methods.
    One of the methods inserts som text in a textArea defined in the child of the abstract class but when I call this method remotly I get a nullpointer exception saying that the textArea has not been initialized. The child ofcause calls super in its constructor.
    So my question is can you not extend an abstract class that register it self in the constructor and then call methods remotly that uses variables that have been initialized in a childs constructor?
    Have your any idea to why I get the nullpointer exception?
    Peter

    >
    This sounds like there might be a misunderstanding
    about the nature of methods and variables. If, for
    instance, your client looks something like this:
    RObject roo = ...// get via RMI
    TextArea text = roo.getTextArea();
    text.setText("...");
    My design is more like this:
    public interface Subscriber extends Remote {
      public void notifySubscriber();
    public abstract class A implements Subscriber {
      a() {
        server.addSubscriber(this);
      public abstract method1();
      // some more abstract methods
      public void notifySubscriber() {
        // do some stuff
        method1();
    public class B extends A {
      JTextArea text;
      A() {
        super();
        text = new JTextArea();
      public void method1() {
        // do some stuff
        // then text is null when called remotly
        text.setText("Hello");
    }Hope this makes my design more clear and you can see the problem.
    Thanks in advance

Maybe you are looking for