"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.

Similar Messages

  • 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.

  • Public main method in a non-public class

    Hi,
    It is said that main method in a java class must be public so that it can be invoked by JVM. This works even if the class itself has default modifier.
    But while programming, any method (be it public) of a class with default access modifier from one package can't be accessed by classes from other packages. For example,
    1. Consider class A in package a.
    package a;
    class A {
    public void methA() {}
    2. Now consider class B in pakage b.
    package b;
    class B {
    void methB() {
    // Here it can't access class A and its method methA()
    So how does JVM invoke the main method of a class with default access modifier. Assume that the class is in some package a.b.c
    Regards,
    Amit

    Hi,
    Maybe this can also be beneficial for you.
    Standalone applications don't necessarily have init and start methods. They must have a public static void main routine to start things off. The main routine typically creates some object of the master class. It can't use any non-static variables or methods in the class with the implied this, since there is no this object. It typically quickly returns. Then the event loop processing starts. Even the static main method must live inside some public class, or at least in the top class, the first class and the class for whom the source file is named. There are no such thing as standalone static methods in Java. The signature of the main class must look exactly like this. Cut and paste it to be sure:

  • 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.

  • Retrieve ServletContext from non-servlet class

    A servlet calls a method which is located in another class which is not a servlet. Within this method of the non-servlet class, i need to access the ServletContext of the servlet that has called the method. What i am currently doing is simply passing the ServletContext as a parameter to the method.
    I would like to avoid passing the ServletContext all the time, so i'm wondering if it's possible, from the non-servlet class, to retrieve the ServletContext of the servlet which has called the method of the non-servlet class.

    Thanks J-Fine, that's a smart suggestion. BTW in the meantime i figured out that passing the ServletContext is not that bad idea, after all it reflects the structure of the app. However if i'll change my mind again i'll do like you suggested.

  • 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

  • Non-abstract methods in a Abstract class

    Abstract Class can contain Non-abstract methods.
    and Abstract Classes are not instantiable as well
    So,
    What is the purpose of Non-abstract methods in a Abstract class.
    since we can't create objects and use it
    so these non-abstract methods are only available to subclasses.
    (if the subclass is not marked as abstract)
    is that the advantage that has.(availability in subclass)
    ??

    For example, the AbstractCollection class (in
    java.util) provides an implementation for many of the
    methods defined in the Collection interface.
    Subclasses only have to implement a few more methods
    to fulfill the Collection contract. Subclasses may
    also choose to override the AbstractCollection
    functionality if - for example - they know how to
    provide an optimized implementation based on
    characteristics of the actual subclass.Another example is the abstract class MouseAdapter that implements MouseListener, MouseWheelListener, MouseMotionListener, and that you can use instead of these interfaces when you want to react to one or two types of events only.
    Quoting the javadocs: "If you implement the MouseListener, MouseMotionListener interface, you have to define all of the methods in it. This abstract class defines null methods for them all, so you can only have to define methods for events you care about."

  • Abstract method versus static and non-static methods

    For my own curiosity, what is an abstract method as opposed to static or non-static method?
    Thanks

    >
    Following this logic, is this why the "public static
    void main" 0r "Main" method always has to be used
    before can application can be run: because it belongs
    to the class (class file)?
    Yes! Obviously, when Java starts up, there are no instances around, so the initial method has to be a static (i.e. class) one. The name main comes from Java's close association with C.
    RObin

  • About abstract method read() in class InputStream

    I would like to know if behind the method
    public abstract int read() throws IOException
    in the abstract class InputStream there is some code that
    is called when I have to read a stream. In this case where can I find
    something about this code and, if is written in other languages, why
    is not present the key word native?
    Thanks for yours answers and sorry for my bad english.

    Ciao Matteo.
    Scusa se ti rispondo in ritardo... ma ero in pausa pranzo.
    Chiedimi pure qualcosa di pi? specifico e se posso darti una mano ti rispondo.
    Le classi astratte sono utilizzate per fornire un comportamento standard lasciando per? uno o pi? metodi non implementati... liberi per le necessit? implementative degli utilizzatori.
    Nel caso specifico la classe InputStream ? una classe astratta che lascia non implementato il metodo read(). Tu nel tuo codice non utilizzerai mai questa classe come oggetto, ma nel caso specifico una sua sottoclasse che ha implementato il metodo read().
    Se vai nelle api di InputStream vedrai che ci sono diverse sottoclassi che estendono InputStream. Guarda ad esempio il codice di ByteArrayInputStream: in questa classe il metodo read() non ? nativo ma restituisce un byte appartenente al suo array interno.
    I metodi nativi (ad esempio il metodo read() della classe FileInputStream) non hanno implementazione java ma fanno invece riferimento a delle chiamate dirette al sistema operativo.
    Per quanto riguarda la classe FilterInputStream di cui parlavi: essa nel suo costruttore riceve un InputStream. Questo significa che si deve passare nel costruttore non la classe InputStream (che ? astratta) ma una classe che la estende e che quindi non sia astratta. Il motivo per il quale FilterInputStream faccia riferimento a una classe di tipo InputStream al suo interno, ? che in java gli stream di input e di output possono essere composti l'uno sopra l'altro per formare una "catena" (a tal proposito vedi per maggiori dettagli uno dei tani articoli che si trovano in rete.... ad esempio ti indico questo http://java.sun.com/developer/technicalArticles/Streams/ProgIOStreams/). Comunque per dirla in due parole: tu puoi voler usare un FileInputStream per leggere un file, ma se hai bisogno di effettuare una lettura pi? efficiente (quindi bufferizzata) puoi aggiungere in catena al FileInputStream un oggetto di tipo FilterInputStream (nel caso specifico un BufferedInputStream che non ? altro che una sottoclasse di FilterInputStream).
    Spero di aver chiarito qualche tuo dubbio!
    Ciao
    Diego

  • A non abstract child class must implement all pure virtual function of  parent abstract class in c++

    Hi,
    In Indesign SDK there is a class  IActionComponent having two pure virtual functions:
    virtual void
    UpdateActionStates(IActiveContext* ac, IActionStateList *listToUpdateGSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil) = 0;
    virtual void
    DoAction(IActiveContext* ac, ActionID actionID, GSysPoint mousePoint = kInvalidMousePoint, IPMUnknown* widget = nil)= 0;
    But, the child class
    class WIDGET_DECL CActionComponent : public IActionComponent
    implements only UpdateActionStates function and not DoAction function.
    There is no compilation error and the code is running fine..HOW
    Can some one please explain me?

    Oops!!! there is a small correction in my C++ program. The JunkMethod is being called from the constructor...like the following code.
    #include <iostream.h>
    #include <stdlib.h>
    class Base
        public:
            Base()
                cout<<"In Base Class constructor..."<<endl;
                JunkMethod();
            void JunkMethod()
                TestAbsFunc();
            virtual void TestAbsFunc()= 0;
    class TestAbstract:public Base
        public:
            TestAbstract()
                cout<<"In Extend Class constructor..."<<endl;
            void TestAbsFunc()
                cout<<"In TestAbsFunc...."<<endl;
    int main()
          TestAbstract test;
          return 0;
    }You can see the change in the constructor of the Base class. JunkMethod is being called, just to bluff the compiler to call the virtual method (so that it won't crib saying that abstract method cannot be called from the constructor). When Java is supporting this functionality without giving any errors, C++ gives errors when you call an abstract method from the constructor or fails to execute when I do some work around like this. Isn't it a drawback of abstract funcationality supported by C++ (I'm not sure if it's a drawback or not)
    Regards,
    Kalyan.

  • About abstract method read() in class InputStream (third message)

    The subclass FilterInputStream is not abstract and extend InputStream: have you ever seen the implementation of that method in the source code available in SDK? It only calls that abstract method!!! I think it is not a very simple problem and anyway the answer is not in my diffrent books. Thanks for your non trivial answer.

    Please post this as a "reply" in your original thread
    http://forum.java.sun.com/thread.jspa?threadID=5192979&tstart=0
    Don't start a new thread, simply reply to one of the other posts in the original thread (there is a button "reply" on the right hand side).

  • Abstract method and class

    I'm a beginner in Java and just learn about abstract method and class.
    However, i am wondering what is the point of using abstract method/class?
    Because when I delete the abstract method and change the class name to public class XXXX( changed from "abstract class XXXX), my program still runs well, nothing goes different.
    Is it because I haven't encountered any situation that abstract method is necessary or ?
    Thanks!

    Yes - you probably haven't encountered a situation where you need an abstract.
    Abstract classes are not designed to do anything on their own. They are designed to provide a template for other classes to extend by inheritance. What you have build sounds like a concrete class - one which you are creating instances of. Abstract classes are not designed to be ever instantiated in their pure form - they act like a partial building block, which you will complete in a class which extends the abstract.
    An example might be a button class, which provides some core functionality (like rollover, rollout etc) but has an empty action method which has to be overwritten by a relevant subclass like 'StartButton'. In general, abstract classes may not be the right answer, and many people would argue that it is better to use an interface, which can be implemented instead of extended, meaning that you can ADD instead of REPLACING.
    Not sure if that helps.. there are whole chapters in books on this kind of thing, so it's hard to explain in a couple of paragraphs. Do some google searches to find out more about how they work.

  • Abstract Method in a Class with implemented method

    I have a class which already has methods Implemented.I mean thse metgods are not abstract.I want only one method to be abstarct which will be overrideen by its subclass or derived Class
    I have never tried this
    Does anyone knows how to do this
    If yes could you give me syntax of the method
    Thanks in advance
    CSJakharia

    javax.swing.JComponent is an example of an abstract
    class with no abstract methods. That is why the
    following works:
    JComponent component = new JComponent(){};
    Not to forget you cannot instantiate abstarct classes
    public abstract class Test
    public String getName()
    return "Mike";
    public static void main(String[] args)
    Test tt = new Test();
    System.out.println(tt.getName());
    }and you would get the error
    The type Test cannot be instantiated.
    You remove the abstract keyword and it would compile
    good.No I am not misinterpreting I know what he is saying but I am closing the door of misinterpretation which I felt was possible. ;)
    cheers

Maybe you are looking for