Abstract class initialisation

Hi,
I have the following problem. What do you suggest?
I have an interface A, abstract class B, B's subclasses C and D, and mainClass
interface A
abstract class B implements A {
    B b;
    public B(String desc)
     if (desc.equals("C")) b=new C();
     else if (desc.equals("D")) b=new D();
class C extends {
  public C() {}
class D extends {
  public D() {}
class mainClass{
  B b=new B("C"); // but B can not be initiated
}B is an abstract class and can not be initiated, I can not define B as normal class, because in B, I define some abstract methods
and want all its subclasses to define them.
What do you suggest me for enhancement?

Hi duffymo,
Your answer quite intersting, can you provide some concrete example!
Do you mean like this:
interface A
class B implements A{
B b;
public B(String desc) {
b=Class.newInstance(desc);
class C extends B
class main {
B=new B(desc);
It seems quite okey, but the problem is that I want subclasses (C and D) to impelement some certain methods. Thus I though B as abstract class
It's called a Factory class or virtual constructor -
that's how you create different runtime types. It's a
GOF Pattern - read about it.
I wouldn't build all that stuff into the abstract B
constructor. That'll force you to modify the B class
every time you add a new subtype - that's not a good
idea. Move that code out into a separate class named
AFactory and give it a static method that does that
creation stuff for you. I know - "That just moves the
changes out of B and into the AFactory" - yes, but I
think that's where they belong.
The java.lang.Class class has a factory method built
into it already - newInstance(). You can use that to
instantiate different subclasses:
A newInstance = Class.newInstance("C");
A anotherInstance = Class.newInstance("D");That's the way I'd do it. - MOD

Similar Messages

  • Class initialisation

    I've simply want to know why class initialisation is done after the constructor of a superclass has been called.
    When the constructor of the superclass uses an abstract function that relies on class attributes it can't work because they aren't initialised until the constructor of the superclass has been finished.The code which was extracted from a concrete problem looks like this:
    public class ClassInitialisation {
         private static int staticcounter = 0;
         public ClassInitialisation() {
              new ClassInit();
         public static void main( String[] args ) {
              new ClassInitialisation();
         public class ClassInit extends BaseClass {
              private Integer myobject = new Integer(-1);
              public ClassInit() {
                   super();
                   Integer result = (Integer) getAbstractFeature();
                   System.out.println( "Value should be 0: " + result.intValue() );
              public Integer getAbstractFeature() {
                   if( myobject.intValue() != -1 ) return( myobject );
                   myobject = new Integer( staticcounter++ );
                   System.out.println( "Object created: " + myobject.intValue() );
                   return( myobject );
              } /* ENDCLASS */
              public abstract class BaseClass {
              private Integer myabstract ;
              public BaseClass() {
                   myabstract = getAbstractFeature();
              public abstract Integer getAbstractFeature();
         } /* ENDCLASS */
    } /* ENDCLASS */
    My original code has done a check against null, so finding the bug was hard since the corresponding object was simply created again but the superclass referred to the previous one.
    Ciao
    Kasimir aka Daniel Kasmeroglu

    That is extremely annoying, isn't it? I expect the designers of the Java language would have a good explanation, but I don't know what it is. I have been hit with this problem twice already in the project I am working on. I have seen this question discussed in these forums before, and "why" is interesting but pointless, because the Java gurus are not going to change it. The only solution is to modify your design so that your BaseClass does not call methods that could be overridden in its constructor. And this is probably not going to be easy; it was not easy for me. Extremely annoying.

  • 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

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • Calling a super.ssuper.method but your super is a abstract class.

    Dear guys,
    Is that possible to invoke your super's super's method but your super is a abstract class?
    like:
    class GO {   public void draw() { } }
    abstract class GORunner extends GO {}
    class GOCounter extends GORunner {
    public void draw() {
    super.super.draw();
    I want to do this because I would like to take advantages of the abstract as an layer to achieve some polymorphism programming Therefore, in the later stage of the programming some code may only refer to GORunner but actually it is holding a GOCounter object.
    Thank!!

    BTW you don't need to write this
    public void draw() {
       super.draw();
    }It works but its basically the same as not having it at all.

  • 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

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • ".. is an abstract class.  It can't be instantiated"

    Does anyone have an idea of how I can get rid of the above error message? Here is a bit of my code:
    import java.io.*;
    import java.util.Vector;
    class Project3 {
    private BiTree company = new BiTree();
    public static void main(String[] args) throws IOException {
    Project3 run = new Project3();
    run.Command();
    public void Command() throws IOException {}
    public interface comparable {
    //not sure if need this in this class, or at all
    public int compare(Object object1,Object object2);
    public void add() {
    Employee newOne = new Employee();
    System.out.println("Enter name");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String name = stdin.readLine();
    System.out.println("Enter title");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    String title = stdin.readLine();
    System.out.println("Enter payrate");
    BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));;
    payrate = Double.parseDouble.stdin.readLine();
    newOne.setTitle(title);
    newOne.setName(name);
    newOne.setPayrate(payrate);
    company.insert(newOne);
    }

    It is not possible to create instances of an abstract class.
    I hope this example helps,
    abstract class Vehicle
    public static void main(String arg[])
    Vehicle a;
    a = new Automobile(); // ok, since Automobile is a kind of Vehicle
    // The class Automobile, a special case of Vehicle
    class Automobile extends Vehicle

  • Abstract Class can't be instantiated

    Hi I'm getting the following error messages while compiling. Does any one have any idea how to get RID of it?
    ERROR MESSAGES:
    EditableHeaderTableExample2.java:48: inner class EditableHeaderTableExample2. MyComboRenderer is an abstract class. It can't be instantiated.
    MyComboRenderer renderer = new MyComboRenderer(items);
    ^
    EditableHeaderTableExample2.java:79: Method redefined with different return type: javax.swing.table.TableCellRenderer getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int) was java.awt.Component getTableCellRendererComponent(javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
    public TableCellRenderer getTableCellRendererComponent(
    ^
    2 errors
    Here is the code:
    EditableHeaderTableExample2.java
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JComponent;
    import javax.swing.JComboBox;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import javax.swing.JTable;
    import javax.swing.plaf.metal.*;
    import javax.swing.JFrame;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableColumnModel;
    import javax.swing.DefaultCellEditor;
    import javax.swing.table.TableCellRenderer;
    import javax.swing.table.DefaultTableCellRenderer;
    public class EditableHeaderTableExample2 extends JFrame {
    public static void main(String[] args) {
    EditableHeaderTableExample2 frame = new EditableHeaderTableExample2();
    frame.setSize(400,300);
         frame.setLocation(100,100);
         frame.setVisible(true);
    public EditableHeaderTableExample2(){
    JTable table = new JTable(10,10);
    TableColumnModel columnModel = table.getColumnModel();
    table.setTableHeader(new EditableHeader(columnModel));
    String[] items = {"Dog","Cat"};
    JComboBox combo = new JComboBox();
    for (int i=0;i<items.length;i++) {
    combo.addItem(items);
    MyComboRenderer renderer = new MyComboRenderer(items);
    EditableHeaderTableColumn col;
    // column 1
    col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(1);
    col.setHeaderValue(combo.getItemAt(0));
    col.setHeaderRenderer(renderer);
    col.setHeaderEditor(new DefaultCellEditor(combo));
    // column 3
    col = (EditableHeaderTableColumn)table.getColumnModel().getColumn(3);
    col.setHeaderValue(combo.getItemAt(0));
    //col.setHeaderRenderer(renderer);
    col.setHeaderEditor(new DefaultCellEditor(combo));
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane);
    class MyComboRenderer extends JComboBox implements TableCellRenderer
    MyComboRenderer(String[] items) {
    for (int i=0;i<items.length;i++) {
    addItem(items[i]);
    public TableCellRenderer getTableCellRendererComponent(
    JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    setSelectedItem(value);
    return this;

    This is not a suggestion, it's a requirement. When you say
    class MyComboRenderer extends JComboBox implements TableCellRendererthe "implements TableCellRenderer" part is a promise that your class will include a method whose signature is
        Component getTableCellRendererComponent(JTable table, Object value,
                                 boolean isSelected, boolean hasFocus,
                                 int row, int column);

  • Difference between abstract class and the normal class

    Hi...........
    can anyone tell me use of abstract class instead of normal class
    The main doubt for me is...
    1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../

    Class vs. interface
    Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
    For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
    With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
    This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
    Interface vs. abstract class
    Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
    Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

  • A Singleton variable in an Abstract Class

    Hello there people
    I have a quick question. I have made an abstract class in which I want to put an identifier (ID) int to be incremented whenever I make any of the concrete class instances that extend this abstract class.
    whould that declairation be as follows?:
    public static int IDAdditionally, I have a quick question about abstract constructors. If constructors are defined in the concrete classes, are their declairations needed in the abstract class?
    and finally, if I wanted to use the int ID (as mentioned above) then would I have to use constructor from the abstract class?
    thanks in advance for the help

    I think the OP would want a constructor in the abstract class to update that variable. Otherwise, he'd have to remember to update it in the constructor for all concrete classes. But, you don't declare constructors for the concrete class in the abstract class. You only declare constructors for the abstract class in the abstract class.

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

  • Casting & abstract class & final method

    what is casting abstract class & final method  in ABAP Objects  give   some scenario where  actually  use these.

    Hi Sri,
    I'm not sure we can be any more clear.
    An Abstract class can not be instantiated. It can only be used as the superclass for it's subclasses. In other words it <b>can only be inherited</b>.
    A Final class cannot be the superclass for a subclass. In other words <b>it cannot be inherited.</b>
    I recommend the book <a href="http://www.sappress.com/product.cfm?account=&product=H1934">ABAP Objects: ABAP Programming in SAP NetWeaver</a>
    Cheers
    Graham

  • 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

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

Maybe you are looking for