Abstract method called in an abstract class

Hello,
I am writing some code that I'd like to be as generic as possible.
I created an abstract class called Chromozome. This abstract class has a protected abstract method called initialize().
I also created an abstract class called Algorithm which contains a protected ArrayList<Chromozome>.
I would like to create a non abstract method (called initializePopulation()) which would create instances of Chromozome, call their method initialize() and full the ArrayList with them.
In a practical matter, only subclass of Algorithm will be used, using an ArrayList of a subclass of Chromozome implementing their own version of initialize.
I have been thinking of that and concluded it was impossible to do. But I'd like to ask more talented peaple before forgetting it !
Thanks,
Vincent

Ok, let's it is not impossible, juste that I had no idea of how doing it :-)
The difficulty is that Algorithm will never have to deal with Chromozome itself, but always with subclass of Chromozome. This is usually not an issue, but in that case, Algorithm is required to create instances of the desired subclass of Chromozome, but without knowing in advance wich subclass will be used (I hope what I say makes any sense).
Actually I may have found a way in the meantime, but maybe not the best one.
I created in Algorithm an abstract method :
protected abstract Chromozome createChromozome()The method initializePopulation will call createChromozome instead of calling directly the constructor and the initialize() method of Chromozome.
Then subclass of Algorithm will implement the method createChromozome using the desired subclass of Chromozome.

Similar Messages

  • "Abstract" method in a non-abstract class

    Hi all.
    I have a class "SuperClass" from which other class are extended...
    I'd like to "force" some methods (method1(), method2, ...) to be implemented in the inherited classes.
    I know I can accomplish this just implementing the superclass method body in order to throw an exception when it's directly called:
    void method1(){
    throw new UnsupportedOperationException();
    }...but I was wondering if there's another (better) way...
    It's like I would like to declare some abstract methods in a non-abstract class...
    Any ideas?

    The superclass just models the information held by
    the subclasses.
    The information is taken from the database, by
    accessing the proper table (one for each subclass).??
    What do you mean by "models the information"?
    You should use inheritance (of implementation) only when the class satisfies the following criteria:
    1) "Is a special kind of," not "is a role played by a";
    2) Never needs to transmute to be an object in some other class;
    3) Extends rather than overrides or nullifies superclass;
    4) Does not subclass what is merely a utility class (useful functionality you'd like to reuse); and
    5) Within PD: expresses special kinds of roles, transactions, or things.
    Why are you trying to force these mystery methodsfrom the superclass?
    It's not mandatory for me to do it... I 'd see it
    just like a further way to check that the subclasses
    implements these methods, as they have to do.That's not a good idea. If the superclass has no relation to the database, it shouldn't contain methods (abstract or otherwise) related to database transactions.
    The subclasses are the classes that handle db
    transaction.
    They are designed as a binding to a db table.And how is the superclass designed to handle db transactions? My guess (based on your description) is that it isn't. That should tell you right away that the subclasses should not extend your superclass.

  • Web dynpro dc compoent controller method call from Java dc class file

    Hi All,
    Is it possible to call a wd java component controller method from a java dc class file?
    I have declared wd java dc as used dc in java dc.Any poiters for the same would be really helpful.
    Thanks in Advance.
    regards
    Radhika Kuthiala

    Hi,
    short answer: No.
    1. using WD references outside of WD DCs is unsupported and will at least show a warning when you try to deploy. Correct usage of runtime dependencies is not predictable.
    2. WebDynpro Controllers have a lifecycle that is controlled by the Framework. Even if you manage to initialize a Controller via "new" and use a method, the Controller will never have all the state-information it contains when started regualary. (think of mapped context, context attributes in general, code called in wdInit ...) I would suppose it is possible to implement a runnable low-profile example that still works, but as soon as you try to use "higher" concepts of WD (which would be the only reason to use a WD Component Controller at all), you will definitely fail.
    3. Think of it as calling EJBs Session Beans via "new", but more complex.
    hope that helps
    Jan

  • Overiding super class method to an abstract  method

    public class Super
    public void doSomethingUseful()
    public abstract class Sub extends Super
    public abstract void doSomethingUseful();
    What is the OO principle behind this?
    When do we need to override a super class method in subclass as an abstract?

    Lets first look at a simple design pattern called "Template Method".
    public abstract class Library
    private void collectBooks()
    // collect books here
    private void putBookInShelf()
    // put books in shelf here
    // abstract method sortBooks()
    public abstract void sortBooks();
    public void processBooks()
    collectBooks();
    sortBooks();
    putBooksInShelf();
    this class is an abstract class giving an abstract method called "sortBooks()", what is it useful for? We can make a subclass and implement sortBooks() to sort the books as we want (title wise, author wise, date wise, publisher wise) and then simply call processBooks() to process them.
    One Sub class may look like:
    public class MyLibrary extends Library
    public void sortBooks()
    // sort books by title b/c I like them sorted out by title
    Another sub-class may look like
    public class HisLibrary extends Library
    public void sortBooks()
    // sort books by Author, b/c he likes his books sorted out by author
    Now client will say:
    public static void main(String str[])
    MyLibrary mylib=new MyLibrary();
    mylib.processBooks(); // books will be processed by sorting them title wise
    HisLibrary hislib=new HisLibrary();
    hislib.processBooks(); // books will be processed by sorting them author wise
    So in Library class, method "sortBooks()" was a template method allowing subclasses to sort the books as they want while all other functionality was implemented by Library class itself.
    Now if we go back to your example, a method which is concrete in super class that you converted into an abstract method in sub class ( doSomethingUseful() ) is now a template method, which alows the sub classes of this subclass to do something useful what they think is useful or in other words you are allowing subclasses of this subclass to implement this template method as they want by using their own algorithm.
    Now why whould you do that? answer is that you don't have access to the code of super class, otherwise you must have made this method abstract in super class in the first place.
    Note that the code may not compile, I tried to come up with an exmple and did not pay attention to compiler demands.
    I think I cleared my point, It was tough to explain though.
    Good Luck.
    Khawar.

  • Abstract method which when implemented will have different parameters

    Hello to all,
    I have an assignment but not looking for someone to do it for me. I am only searching for a suggestion on how to do the following.
    Imagine having an application that needs to provide an estimate of the rent for different buildings.
    Basically I start with by having a class name Building. This class has an abstract method called estimateRent.
    I then create two classes that extend the class Building which are named Apartment and House. Both need to have the method estimateRent.
    However the problem is that the rent for the Apartment is calculated on the nights passed in the flat and the people in it, while the rent for the House is just calculated on a month bases.
    This means the estimateRent method requires to have different parameters depending if it is implemented inside the Apartment class or the House class.
    Now I only know of two options.
    The first option is to not declare the estimateRent method as an abstract method inside the Building class and just implemented inside the Apartment and House with different parameters. I do not like this option since in the future if a new Building comes in then I would like to impose the fact that that object needs to have a calculate method.
    The second option is to make the estimateRent method as abstract inside the Building class however takes a parameter of either a String array or else a Map. Then the estimateRent within the Apartment class would search for the elements tagged as nights and people, and the House class would only search for the elements tagged as months!
    However do not know if there are any other, better ways on how to do this. I am using Java 1.4 however if you only have answers for Java 5.0 then please post them again since I always like to learn something new :)
    Thank You for any comments.
    tx

    The implementation changes, yes.Yes that I could understand in the Strategy Pattern (in the document I read it was being compared with the Template Pattern).
    Then you need to refactor your design.I tought about that, however if you read my first post you will notice that I have different criteria on which the costs need to be estimated. While the costs for a flat are estimated on the people staying in and nights slept there, the costs for the house are based only on the months stayed there regardless of the people living in. Now for me I feel that it is bad programming practice to create one method that can have all the parameters required for any scenario. I mean the following is NOT something I am going to do:
    estimateCosts(int nights, int people, int months ... etc);
    That's not a very elegant way of going about it.
    What is the "Context" going to have?Yep I agree, but so far my limited brain has only come up with that! I am open to any other sugestion! always if i understand it first!
    Basically the Context would better be named as Criteria and it would be an interface as follows:
    interface Criteria{}
    Then I would create two classes that implement the Criteria object as follows:
    class AppartmentCriteria implements Criteria{
    public Result estimateCosts(int nights, int people);
    class HouseCriteria implements Criteria{
    public Result estimateCosts(int months);
    Now when I recieve the inputs, depending on the scenario the Criteria is typecasted and the correct parameters passed and we recieve the Result.
    I feel the above sucks since I am not seeing it as an object oriented way of doing this out! Is there any other sugestions! The refactoring thing I am intrested in! however really I can not see how such a call to that method could be refectored!
    Thank You,
    tx.
    PS: Sun has blocked my other account as well, and this time they did not even send me an email to confirm that I was registered successfuully :( Is there someone I can contact on this? I guess next time I will reply with tx53m :)

  • Abstract Method Overriding Problem

    I have an abstract class called "Employee" with an abstract method called "ReturnBasicInfo()" defined.
    I have two subclasses, SalariedEmployee and HourlyEmployee, and each has their own version of ReturnBasicInfo(). The compiler is not letting me do this, however, and I have no idea why.
    I keep getting this error:
    SalariedEmployee.java:6: SalariedEmployee is not abstract and does not override
    abstract method returnBasicInfo() in Employee.The abstract method signature is this:
    public abstract String returnBasicInfo(Employee e);Any idea why this might be happening? I have another abstract method called toVector() that's overriden in the subclasses and that one works fine, so I'm stumped on this. The only difference between the two is that this method takes arguments and the other doesn't. Is that why it can't be overriden?
    Thanks in advance for any help!

    "...In the instructor's example code, he actually
    overrode toString with this method. I thought I might
    be using the real toString(), though, so that's why I
    changed the name to returnBasicInfo(). I didn't end up
    using toString(), though. Maybe I ought to go back to
    calling it toString()..."
    Yes, this SHOULD be overridden in toString(). Do go
    back to it.
    The "real" toString()? Do you mean the default
    version in java.lang.Object, the one that just prints
    out the object reference when it's called?
    Hmm, I guess. I got confused because I'm swapping between String and double values a lot. Taking in an entered number as a String and converting it to a double.
    I think I originally confused toString() with String.valueOf().
    I wouldn't have getYearlySalary() for SalariedEmployee
    and getHourlySalary() for HourlyEmployee. That
    defeats the purpose of polymorphism and dynamic
    typing. Yes, but I do have one polymorphic method --pay(). Each Employee is paid a different way. The one method we were supposed to be able to call on all Employees is just pay(). There is one version of pay() for HourlyEmployees that uses gethourly_rate() and gethours_worked() to get hourly rate and hours worked. The other version of pay() in SalariedEmployees takes in their yearly salary and number of pay periods worked.
    Better to have a getSalary() method in your
    Employee interface and let each subclass implement it
    the way they want to. SalariedEmployee will return
    their yearly salary, HourlyEmployee will return
    hourlySalary*hoursWorkedOK, that's one idea.
    But darnit, I would still like to know how to get my original design to work. So I should change returnBasicInfo() to toString(), you think?

  • Abstract methods and subclasses

    I have a class, DfContainer that has a method whose return type is of an abstract class, DfObject.
    There are several classes that extend the abstract class. Each of them has methods that are unique to them.
    But in order to be able to execute the methods using the object returned through the method in DfContainer, I need to define each method as abstact in DfObject.
    Now say, I need a method called getNames() in the class DfNames that extends DfObject, and I need a method called getRanks() in DfOrganization that also extends DfObject.
    I would define those two methods as abstract in DfObject. But, I would need to add getRanks() to DfNames, and add getNames() to DfOrganization, even if I don't need them there.
    That's what I'm doing right now. If I don't cast the object returned from the method in DfContainer to a subtype of DfObject, is this the correct approach?
    Thanks,
    Moshe

    Why don't you define an empty method body in the abstract class, that does not have to be overridden in the subclass.
    An abstract class can contain fully implemented methods. You can then override them or not as you choose. You don't have to define your individual methods as abstract.
    Look at the way the various listeners and adapters are done in AWT. You have a listener that's an interface, then a dummy class that provides do-nothing implementations for all methods in the interface, so when you want to override one method you only need to override that specific method, not all the methods in the interface. You should be able to do something similar.

  • Getting error while creating abstract method

    hi folks,
    i facing issue for ABSTRACT Class.
    I am trying to create abstarct method, (refered example from saptechnical site),
    I created one attribute i-num, created one method AREA, in  implementation area , i made it as Abstract, then i did syntax check, then it is giving below error.
    *Class ZTEST_CLASS01_AB,Method AREA
    The abstract method "AREA" can only be implemented after its
    redefinition (METHODS AREA REDEFINITION).*
    i tried all the ways..
    created subclass for this, i writted some code in AREA of Sub-class, there it is giving dump, because first one is not activated properly..
    could you please somebody help me on this.
    Sri

    Hello Arshad,
    Create a class(ZABSTRACT) and make its type as Abstract( Which means atleast one of its methods is abstract)
    We can have abstract classes with all it's methods as non-abstract or concrete. A small example is given below:
    CLASS gcl_abstract DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS concrete. "Concrete
    ENDCLASS.                    "gcl_abstract DEFINITION
    *       CLASS gcl_abstract IMPLEMENTATION
    CLASS gcl_abstract IMPLEMENTATION.
      METHOD concrete.
        WRITE: / `I'm a concrete method`.
      ENDMETHOD.                    "concrete
    ENDCLASS.                    "gcl_abstract IMPLEMENTATION
    *       CLASS gcl_abstract_sub DEFINITION
    CLASS gcl_abstract_sub DEFINITION INHERITING FROM gcl_abstract.
      PUBLIC SECTION.
        METHODS concrete REDEFINITION.
    ENDCLASS.                    "gcl_abstract_sub DEFINITION
    *       CLASS gcl_abstract_sub IMPLEMENTATION
    CLASS gcl_abstract_sub IMPLEMENTATION.
      METHOD concrete.
        super->concrete( ).
        WRITE: / 'Abstract class might not have abstract methods at all!'.
      ENDMETHOD.                    "concrete
    ENDCLASS.                    "gcl_abstract_sub IMPLEMENTATION
    START-OF-SELECTION.
      DATA: go_abstract TYPE REF TO gcl_abstract_sub.
      CREATE OBJECT go_abstract.
      go_abstract->concrete( ).
    Although i will agree there is no point in making a class as abstract & having no abstract method
    @Sri: Looks like you're trying to implement the abstract method "AREA" in the abstract class hence the error. For abstract method you cannot define their implementation in the corres. abstract class.
    BR,
    Suhas
    Edited by: Suhas Saha on Mar 30, 2011 12:04 PM

  • Abstract method in Interface

    Why are we able to define abstract method in an Interface?
    I don't imagine when I must use an abstact method in a interface.
    Does anybody ever use this?

    Thanks for your answer.
    I can declare an abstract class which implementes an
    interface.
    The abstract class doesn't require the implementation
    of the methods
    declared in the interface.
    Why this?Because the class is abstract.
    A concrete class must provide (or inherit) implementations for all abstract methods in all its ancestor classes and for all methods in all interfaces it implements (and remember, all methods in an interface are abstract).
    If a class does NOT have an implementation for one or more of those methods, the class must be declared abstract to indicate that.
    I don't understand because an abstract class can
    implements an interface!Any class can be declared abstract (except final classes, I think).
    Any class that doesn't have implementations for all its methods (including those from interfaces) MUST be declared abstract.

  • Static abstract method equivalent?

    From the forum thread:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=5202376
    baftos wrote:
    On the othe hand OP had a legitimate desire.
    How can a superclass force its subclasses to
    provide a certain class (as opposed to instance) behaviour?
    Do other languages provide something like this?I like to have a static abstract method in a super abstract class:
    public static abstract Behavior getClassMarker();And each sub concrete class should have:
    public static Behavior getClassMarker(){
      return new Behavior(-- parameters --);
    }Could we have an equivalent that current Java allows? Or, do we see some good news on the horizon?

    Normally you create an instance with the metadata for the type, which annotations let you do:package dog;
    abstract class Dog {
      abstract String getBark() ;
      Dog () {
        assert (getBreed() != null);
      DogBreed getBreed () { return getClass().getAnnotation(DogBreed.class); }
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface DogBreed {
      String genericBark () ;
      String name () ;
    @DogBreed(name="Bulldog", genericBark="GrrrGrrrGrrr")
    class Bulldog extends Dog {
      String getBark() {
        return "Grrr";
    @DogBreed(name="Pomeranian", genericBark="Pirrr")
    class Pomeranian extends Dog {
      String getBark() {
        return "Sausages";
    public class DogAnnotationTest {
      public static void main (String...args) {
        Pomeranian pomme = new Pomeranian();
        System.out.println("The generic bark of the " + pomme.getBreed().name() + " breed is "
              + Pomeranian.class.getAnnotation(DogBreed.class).genericBark() + " but our  pomme cries "
              + pomme.getBark() + " for a jerky, his favorite food");
    }The limitation is that you can only annotate with simple types, so you're stuck with the abstract factory pattern if you want the creation. Not that that's a bad thing, as it lets you create instances of classes which haven't been loaded yet.

  • Can i call non -abstract method in abstract class into a derived class?

    Hi all,
    Is it possible in java to call a non-abstract method in a abstact class from a class derived from it or this is not possible in java.
    The following example will explain this Ques. in detail.
    abstract class A
    void amethod()
    System.out.println(" I am in Base Class");
    public class B extends A
    void amethod()
    System.out.println(" I am in Derived Class");
    public static void main (String args[])
    // How i code this part to call a method amathod() which will print "I am in Base Class
    }

    Ok, if you want to call a non-static method from a
    static method, then you have to provide an object. In
    this case it does not matter whether the method is in
    an abstract base class or whatever. You simply cannot
    (in any object oriented language, including C++ and
    JAVA) call a nonstatic method without providing an
    object, on which you will call the method.
    To my solution with reflection: It also only works,
    if you have an object. And: if you use
    getDeclaredMethod, then invoke should not call B's
    method, but A's. if you would use getMethod, then the
    Method object returned would reflect to B's method.
    The process of resolving overloaded methods is
    performed during the getMethod call, not during the
    invoke (at least AFAIK, please tell me, if I'm wrong).You are wrong....
    class A {
        public void dummy() {
             System.out.println("Dymmy in A");
    class B extends A {
         public void dummy() {
              System.out.println("Dymmy in B");
         public static void main(String[] args) throws Exception {
              A tmp = new B();
              Class clazz = A.class;
              Method method = clazz.getDeclaredMethod("dummy", null);
              method.invoke(tmp, null);
    }Prints:
    Dymmy in B
    /Kaj

  • Parent constructor calls abstract method

    Hi everybody!
    I'm wondering if there is something wrong with java or if the idea is just too ill?
    Anyway, I think it would be great if this hierachy would work...
    Two classes A and B.
    Class A defines an astract method.
    In A's constructor this abstract method is called.
    Class B extends A and provides an implementation for the abstract method in A.
    Class B also defines a member variable that is set in B's implementation of the abstract method.
    In class' B constructor the parent constructor A() is called.
    example:
    public abstract class A {
      public A() {
        createComponents();
      public abstract void createComponents();
    public class B extends A {
      private String string = null;
      public B() {
        super();
        System.out.println("B::B() " + string);
      public void createComponents() {
        System.out.println("B::createComponents() begin");
        string = new String("test");
        System.out.println("B::createComponents() " + string);
      public void describe() {
        System.out.println("B::describe() " + string);
      public static void main(String[] args) {
        B b = new B();
        b.describe();
    }running the code above produces the following output:
    B::createComponents() begin
    B::createComponents() test
    B::B() null
    B::describe() null
    why is the string member variable null in B's constructor??
    thanks in advance
    Peter Bachl
    Polytechnic University of Upper Austria, Hagenberg
    [email protected]

    The answer is that the call of the super-constructor
    is allways done before the initialization
    of the member variable. That's all and that's the
    normal behavior.
    order :
    - initialization of static variables
    - call to the super-constructor
    - initialization of the instance variables
    - execution of the constructor
    Since this is the advanced forum it is relevant to point out that that is not exactly true.
    There is a step in java that 'initializes' member variables before any constructors are called, super or other wise.
    From the JLS 12.5...
    Otherwise, all the instance variables in the new object, including those declared in superclasses, are initialized to their default values (4.5.5)
    Using the following code as an example
      class MyClass
         int i1;
         int i2 = 1;
    .When creating an instance of the above there will be three 'initializations'
    // Part of object creation...
    i1 = 0; // The default value
    i2 = 0; // The default value
    // Part of construction...after super ctors called.
    i2 = 1; // The variable initializer (see step 4 of JLS 12.5)
    Unfortunately the descriptions are rather similar and so confusion can result as to when the assignment actually occurs.

  • Abstract methods in ByteBuffer class

    I'am a little confused with abstract methods get() and put() in ByteBuffer class.
    Java API says:
    public abstract class ByteBuffer
    extends Buffer implements Comparable
    // This is a partial API listing
    public abstract byte get( );
    public abstract byte get (int index);
    public abstract ByteBuffer put (byte b);
    public abstract ByteBuffer put (int index, byte b);
    }Question is:
    How can I call methods get() and/or put() when they are abstract - not implemented in ByteBuffer class?
    Thanks

    Yeah, it's a subclass of ByteBuffer. You can find out more about the class by using introspection.
    But, you don't have to, to use this API. This is called "design-by-contract" (well, part of it anyway), and that's why the class is hidden with respect to the API docs. The idea is that an API is kind of like a contract, an agreement between the designer and the user of the API. The user of the API is given just what s/he needs to do the job. The designer might implement the API with more stuff that is immediately apparent, but the user doesn't need to know that stuff to use the API. This provides a good layer of abstraction around the API and makes code more flexible.
    So, it's good to know how these things work -- that the ByteBuffer contract is serviced by hidden implementing classes -- but you don't have to know that to use ByteBuffer, and in fact you'd probably only make things difficult (buggy and hard to maintain) if you wrote code that used the fact that apparently the implementing subclass of ByteBuffer is HeapByteBuffer.

  • Calling abstract method inside constructor

    what will happen if you call abstract method inside a constructor ?

    AMARSHI wrote:
    Then wat is the purpose of that object then.
    When u create an object then the control will move to the default constructor,If there is one. Not all classes have default constructors. Some c'tor will be called though.
    inside the constructor u r having an abstract method.
    But theere are 2 cases now:
    1 the top-level class is an abstract class
    2 the abstract class is an inner class.
    1. for case 1 , u cannot create an object ,so no need of having the constructor.Yes, you can create an object. You can instantiate a concrete subclass. The abstract parent's constructor is still called, and that c'tor may call an abstract method, which will be implemented in the concrete subclass, or some class between it and the parent.
    2.for case 2 u cannot have an object like:
    outerClass obj = new innerAbstractClass()I have no idea what you're talking about here.

  • Call an abstract method

    Hello developers,
    I am trying to implement the following (simple) classes:
    class abstract_class definition abstract
         public
         create public .
         protected section
              methods parse_string abtract
                   importing
                        value(i_str) type string.
              methods to_table.
    endclass.
    class abstract_class implementation.
         method to_table.
              me->parse_string( str ).
         endmethod.
    endclass.
    class other_class definition
         public
              inheriting from abstract_class
              final
              create public .
         protected section.
              methods parse_string redefinition.
    endclass.
    class other_class implementation.
         method parse_string.
    *        some codes         
         endmethod.
    endclass.
    I have instantiated the class other_class. But when I call the method to_table, I am getting the error "CALL METHOD NOT IMPLEMENTED" on the method parse_string. Where is my mistake ?
    Thank you for your replies.
    Best regards,
    Nicolas

    Hello everyone,
    First of all, thank you for all your reply.
    During the night, I have thought to my problem and I found the solution. In fact, I made a (very) great mistake. Here is my code:
    CLASS abstract_class IMPLEMENTATION.
         method constructor.
              me->to_table( ).
         endmethod.
         method to_table.
              me->parse_string( a_string ).
         endmethod.
    ENDCLASS.
    CLASS other_class IMPLEMENTATION.
         method constructor.
              call method super->constructor.
         endmethod.
         method parse_string.
    *          some code
         endmethod.
    ENDCLASS.
    The problem is: I call the method parse_string of my child class (with the instruction me->parse_string) before my child class is instantiated... (Now, I can jump out the window.) Vadim Vologzhanin 's reply helped me by asking where I instantiated my child class.
    Thank you !
    Best regards,
    Nicolas

Maybe you are looking for