Calling a constructor of an object that extends another object

suppose you have the source:
class A {
public int x = 1;
public int y = 5;
public A(){y = 6;)
class B extends A {
public B(){}
public B(int a) { super(a); }
Now suppose in the main function you say
B b1 = new B();
I would think the value of x is 1 which it is, but the value of y is 6, why is this, I did not call the A constructor or does an object call the parameterless constructor of its superclass automatically. If that is the case, it will clarify to me why y gets the value of 6 and not 5.

Unless you specify a super call, it will be done. The next two constructors are the same:public B () {
    x = 2;
public B () {
    super ();
    x = 2;
}Another thing for you to try: remove the A () constructor (but keep the A (int)) and see if B will still compile.
Kind regards,
Levi

Similar Messages

  • Calls to methods in a class that extends Thread

    Hello,
    I have some code that I am initiating from within an ActionListener that is part of my programs GUI. The code is quite long winded, at least in terms of how long it takes to perform. The code runs nicely, however once it is running the GUI freezes completely until operations have completed. This is unacceptable as the code can take up to hours to complete. After posting a message on this forum in regard to the freezing of the GUI it was kindly suggested that I use multi-threading to avoid the unwelcome program behaviour.
    The code to my class is as follows:
    public class FullURLAddress
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    I have changed the above code to make use of multithreading by making this class extend Thread and implementing the run() method as follows:
    public class FullURLAddress extends Thread
      private boolean success_flag = true;
      private BufferedReader iN;
      private Document dT;
      private EditorKit kT;
      private Element lmNt;
      private ElementIterator lmIterate;
      private XURL[] compAddress;
      private int countX = 0;           //Tracks Vector vT's size.
      private int countY = 0;           //Tracks Vector vS's size.
      private int xURLcount = 0;        //Tracks XURL objects instantiated by this FullURLAddress object.
      private SimpleAttributeSet simpAtSet;
      private String aURL;              //Contains original (Xtended) URL!
      private String fileType;
      private String indexContent;
      private String[] parseURL;
      private String[] finalStrings;
      private String[] sortStrings;
      private URL indexConnect;
      private URLConnection iconn;
      private Vector vT;            //Stores href information, from targeted URL's HTML souce code.
      private Vector vS;            //Stores sorted HREF info ".jpg" and ".gif" only (no: png, tiff, etc).
      public FullURLAddress(String aURL)
        this.aURL = aURL;
      public void run()
        try{
          indexConnect = new URL(aURL);
          iconn = indexConnect.openConnection();
          iN = new BufferedReader(new InputStreamReader(iconn.getInputStream()));
            /* Document creation, analysis objects instantiated */
          vT = new Vector();
          vS = new Vector();
          kT = new HTMLEditorKit();
          dT = kT.createDefaultDocument();
          dT.putProperty("IgnoreCharsetDirective", Boolean.TRUE);
            /* Iterate through document and store all HREF values */
          kT.read(iN, dT, 0);
          lmIterate = new ElementIterator(dT);
          while((lmNt = lmIterate.next()) != null)
            simpAtSet = (SimpleAttributeSet)lmNt.getAttributes().getAttribute(HTML.Tag.A);
            if(simpAtSet != null)         //As long as there are A tags to be read...
              vT.addElement(simpAtSet.getAttribute(HTML.Attribute.HREF));
              countX++;//Tracks number of HREF occurences occur, giving better control of the Vector.
        }catch(MalformedURLException e){
          success_flag = false;
          System.out.println("FullURLAddress object has encountered a "+
                             "MalformedURLException at: "+aURL);
        }catch(IOException e){
          e.getMessage();
          success_flag = false;
        }catch(BadLocationException e){
          e.getMessage();
          success_flag = false;
        /* Searches through all HREF attributes that are now stored in Vector
           vT for occurences of the character string ".htm" */
        sortStrings = new String[countX];
        for(int i=0;i<countX;i++)
          sortStrings[i] = (String)vT.elementAt(i); //Vector Strings transfered into array.
          if(sortStrings.endsWith("gif")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("GIF"))
    vS.addElement(sortStrings[i]);
    countY++;
    if(sortStrings[i].endsWith("jpg")) // Does href value end with ".jpg"?
    vS.addElement(sortStrings[i]); // If so add it to the sorted Vector vS.
    countY++;
    if(sortStrings[i].endsWith("JPG"))
    vS.addElement(sortStrings[i]);
    countY++;
    finalStrings = new String[countY];
    for(int j=0;j<countY;j++)
    finalStrings[j] = (String)vS.elementAt(j);
    /* What happens with these methods, will they need to have their
    own treads also? */
    public int getCount()
    return countY; //Returns number of instances of htm strings
    } //ending with either "jpg" or "gif".
    public String[] xurlAddressDetails()
    return finalStrings;
    Are there any special things that I need to do in regard to the variables returned by the getCount() and xurlAddressDetails() methods. These methods are called by the code that started the run method from within my GUI. I don't understand which thread these methods are running in, obviously there is an AWT thread for my GUI and then a seperate thread for my FullURLAddress objects, but does this new thread also encompass the getCount() and xurlAddressDetails() methods?
    Please explain.
    This probably sounds a little wack, but I don't understand what thread is responisble for the methods in my FullURLAddress class aside of course from the run() method which is obvious. Any help will be awesome.
    Thanks
    Davo

    Threads are part of code that allows you to run multiple operations "simultaneously". "Simultaneously", because threads are not run actually simultaneously in any one-CPU machine. Since you most propably have only one CPU in your system, you can only execute one CPU instruction at time. Basically this means that your CPU can handle only one java-operation at time. It does not matter if you put some code in thread and start it, it will still take up all CPU time as long as the thread runs.
    So you would need a way to let other threads run also, for that purpose thread contains a yield feature that allows you to give time for other threads to run.
    http://java.sun.com/j2se/1.4.1/docs/api/java/lang/Thread.html#yield()
    You need to use thread's yield() method in your thread code, in a place you want to give other threads time to run. Also bear in mind that if you yield your first thread run to allow second thread to run, you also need to add yield to the second thread also. If you don't, after yielding the first thread, the second thread will eat up all CPU time until it finishes, thus meaning the rest of your first thread will be run after second thread is done.
    One good place to execute yield() is usually at the end of a loop, for example 'for' or 'while' loop. This way you prevent for example while-deadlocks.
    Here is a java thread tutorial, worthy reading:
    http://java.sun.com/docs/books/tutorial/essential/threads/

  • Custom mxml component extending another mxml component

    I want to create a custom mxml component that extends another mxml component. Bacially I want structure like Group -> BaseMXMLComponent -> MyMXMLComponent. I understand that it used to be the case that trying to add child component to MyMXMLComponent would throw "Error: Multiple sets of visual children have been specified for this component (base component definition and derived component definition)." error. But i've been reading few articles that says this has been fixed in Flex 4.
    My question is.. is it an actually fixed, documented, and supported behavior of Flex 4? or just an undefined behavior that appears to be "fixed" but can change on future update?

    I dont know what is happening inside datagrid.But If
    you want to maintain a single instance you could use singleton design pattern
    read about it
    http://en.wikipedia.org/wiki/Singleton_pattern
        public class Singleton
            private static var instance:Singleton= new Singleton();
            public var userdata:*; // keep user object
            public function Singleton()
                if (instance != null) { throw new Error('Cannot create a new instance.  Must use Singleton.getInstance().') }
            public static function getInstance():Singleton
                return instance;

  • Mock objects calling parent constructor

    I'm trying to create some tests in which I'm providing a mock object to the constructor of my test objects and testing that appropriate methods are called in the mock. The objects I'm mocking only have a few public methods so I created an inner class that extends the object I'm trying to mock and just records which method was called. However, when I run the test it fails because the mock object calls the default constructor of the object of it's parent; causing the entire application to run. I'm trying to figure out a way around this.
    Now I already know a solution that would work, creating a second constructor in the object I'm mocking which does nothing, then call the fake constructor from my mock object instead of the default constructor. The solution dosn't feel very elegent though, I'm wondering if I'm missing a simpler solution?

    dsollen wrote:
    I'm testing JMS communication between two applications. Each topic Listener has a reference to the main class of the respective applications to communicate with them.I still don't see why a call to the constructor should start the program. Change the design so that doesn't happen. You should instead provide a start method.
    Kaj

  • Help and some explanation how to get a Microsoft.Office.Tools.Excel.Worksheet host item that extends the functionality of the current Microsoft.Office.Interop.Excel.Worksheet object

    Hello,
    I would use some help and more info about how to get host object that extends the functionality of my current Interop.Excel.Worksheet object. I read this artical: https://msdn.microsoft.com/en-us/library/ee794671.aspx where I can call this function
    GetVstoObject to get host object. But I see that here I need to pass the Globals.Factory object as second parametar. Can someone give me more details about that parameter and how to access it? I would like to get host object so I can access extension
    property, since my interop excel worksheet doesn't have it.  
    I am using Visual Studio 2013 for developing Excel addin. Using Excel 2010.
    Thanks in advance for help.
    Regards,
    Zeljka

    Hi Zeljka,
    >>I am using the Microsoft Office PIAs, so my question is how to access this automatic generated class Globals in my case?   <<
    Sorry, I am not able to understand the application you were developing exactly. From the orgnal post, you were developing an application level add-in, however based on the description above, it seems that you were building an console or Windows form application
    to automate Office application.
    If you were developing Office automation, the host item can't work for this secnario since it should run under the VSTO runtime.
    If I misunderstood, please feel free to let me know.
    Regards & Fei
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Create an object instance without calling its constructor?

    Hi,
    Sometimes it's useful to create object instances without calling their constructor. When? For example object deserialization.
    By default when deserializating an object, the instance in the VM is created by calling the default constructor of the first non Serializable super-class (if you don't have such you're in trouble). I think that the db4o object database don't even call any constructor you may have written.
    So such thing exists, but how is this possible? I fugured out that sun's deserialization mechanism first finds the constructor of the first non Serializable super-class and then:
    cons = reflFactory.newConstructorForSerialization(cl, cons); Here I'm stuck.
    Here's the source of the method for finding serializable constructor:
         * Returns subclass-accessible no-arg constructor of first non-serializable
         * superclass, or null if none found.  Access checks are disabled on the
         * returned constructor (if any).
        private static Constructor getSerializableConstructor(Class cl) {
         Class initCl = cl;
         while (Serializable.class.isAssignableFrom(initCl)) {
             if ((initCl = initCl.getSuperclass()) == null) {
              return null;
         try {
             Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
             int mods = cons.getModifiers();
             if ((mods & Modifier.PRIVATE) != 0 ||
              ((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
               !packageEquals(cl, initCl)))
              return null;
             cons = reflFactory.newConstructorForSerialization(cl, cons);
             cons.setAccessible(true);
             return cons;
         } catch (NoSuchMethodException ex) {
             return null;
        }So any info about this ReflectionFactory, and the problem as a whole?
    Thanks.

    So the question is how to create object instance without initializing it (calling the constructor)? And if you have any info about ReflectionFactory it will be useful too.
    When serializing an object you save all its fields and some extra info. When you deserialize it you have to reconstruct it, by copying the fields back, but not to reinitialize.
    import java.lang.reflect.*;
    import java.io.Serializable;
    import java.security.AccessController;
    import sun.reflect.ReflectionFactory;
    public class Test0 implements Serializable {
        public Test0() {
            System.out.println("Test0");
        public static void main(String[] args) throws Exception {
            Constructor<Test0> constr = reflectionFactory.newConstructorForSerialization(Test0.class, Object.class.getConstructor(new Class[0]));
            System.out.println(constr.newInstance(new Object[0]).getClass());
        private static final ReflectionFactory reflectionFactory = (ReflectionFactory)
         AccessController.doPrivileged(
             new ReflectionFactory.GetReflectionFactoryAction());
    }When you execute this piece you get:
    class Test0

  • How to call a class that extends a frame from a panel ?

    How to call a class that extends a frame from a panel ?
    I am trying to create an application say "Videoshow"
    Videoshow has a panel which in turn consists of 2 components : 1]a textarea( to show the contents of a page) and 2] a mediaclip(to show the video).
    Now I have an application "MediaApplication"(to show the videoclip) which extends Frame (Code from Java 2 Unleashed, Chap 21). I want to show this MediaApplication in Component 2 of the above panel. But when I do this, I only see the MediaApplication frame instead of the whole SlideShow.
    I want to do something likethis.
    VideoShow :
    |---------------------------------|-------------------|
    | |
    | (Comp 1) | (Comp 2)
    | TEXTAREA | Video Clip
    | |(MediaApp entends Frame)
    |---------------------------------|-------------------|
    What is the best way to achieve this ? Also which component can I use to show the videoclip ?

    im not familiar with the code you mention from Java 2 Unleashed, but your best bet is to read up on Swing a bit - so you get an idea of how Swing containers and components work - then im sure you'll find a solution to your problems. Then if you encounter any difficulties whilst your attempting to do that, post your code in the Swing forum and im sure someone will help you.

  • SerialVersionUID of a class that extends a serializable object

    I have class Foo that implements Serializable. In Foo, I have manually hardcoded the serialVersionUID as: private static long serialVersionUID = -7589377069041161459L;Now I created a class SubFoo that extends Foo, but I have not overrided the serialVersionUID. However, when I run serialver command on SubFoo I get 2152116903368641813L, instead of my hardcoded serialVersionUID. Shouldn't I be getting my hardcoded value?
    This is important to me because I am running into a Serialization Mismatch on about 100+ subclasses of Foo. So I was hoping to fix this by adding a hardcoded serialVersionUID into the one parent class and hoping not to manually change 100+ subclasses.

    Now I created a class SubFoo that extends Foo, but I
    have not overrided the serialVersionUID.When the compiler calculates the serialVersionUID, it hashes many things, including the fully qualified class name.
    So, even though you may not have added any member variables, the serialVersionUID has changed because the class name has changed from Foo to SubFoo.
    You need to manually specify / hardcode the serialVersionUID in all subclasses.
    You can see section 12.24.4 of The Java Programming Language, 2nd Ed. for more details.
    Best,
    Garrett

  • Pass a value to a class that extends AbstractTableModel

    Hi
    I have a problem with a table model that I cannot find a way of overcoming.
    I have created a class called MyTableModel that extends AbstractTableModel.
    MyTableModel creates and uses another class that I have defined in order to retrieve records from a database, MyTableModel fills the table with these records.
    However, I wish to alter my class in order to provide an int parameter that will act as a �where� value in the classes sql query.
    The problem is this, I cannot work out how to pass a value into MyTableModel. I have tried creating a simple constructor in order to pass the value but it doesn�t work.
    My code is shown below:
    import BusinessObjects.JobItemClass;
    import DBCommunication.*;
    import java.util.ArrayList;
    import javax.swing.table.AbstractTableModel;
    public class MyJobItemTableModel extends AbstractTableModel
      public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];
      public void fillTable()
          if(c > 0)
            for (int i = 0; i < c; i = i + 1)
              this.setValueAt(((JobItemClass) items.get(i)).getItemNumber(), i, 0);
              this.setValueAt(((JobItemClass) items.get(i)).getDescription(), i, 1);
              this.setValueAt(((JobItemClass) items.get(i)).getCostPerItem(), i, 2);
              this.setValueAt(((JobItemClass) items.get(i)).getQuantity(), i, 3);
      public void setJobNo(int s)
          jobNo = s;
      public int getColumnCount()
          if(c > 0)
            return table[0].length;
          else
              return 0;
      public int getRowCount()
        return table.length;
      public Object getValueAt(int r, int c)
        return table[r][c];
      public String getColumnName(int column)
        return columnName[column];
      public Class getColumnClass(int c)
        return columnType[c];
      public boolean isCellEditable(int r, int c)
        return false;
      public void setValueAt(Object aValue, int r, int c)
          table[r][c] = aValue;
    }Any advice will be appreciated.
    Many Thanks
    GB

    your JobAllItems is created before constructor code is run (since it is initialized in class member declaration)
    use something like
    public MyJobItemTableModel(int j)
          jobNo = j;
          items = (new JobAllItems(jobNo)).getItems();
          c = items.size();
          table =   new Object[c][4];
      int jobNo;
      ArrayList items;
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c;
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] ;instead of
    public MyJobItemTableModel(int j)
          jobNo = j;
      int jobNo;
      JobAllItems jobItems = new JobAllItems(jobNo);
      ArrayList items = jobItems.getItems();
      String columnName[] = { "Item Number", "Item Description", "Cost per item", "Quantity" };
      int c = items.size();
      Class columnType[] = { Integer.class, String.class, Double.class, Integer.class };
      Object table[][] =  new Object[c][4];

  • Copy constructor and temporary objects in C++

    I'd need some clarification on how constructor works when the argument is  a temporary object. I defined a dummy MyVect class with operator+ and copy constructor:
    class MyVect {
    public:
    MyVect() {
    cout << "Constructor" << endl;
    MyVect(const MyVect &vect){
    cout << "Copy Constructor" << endl;
    ~MyVect() {
    cout << "Destructor" << endl;
    MyVect operator+(const MyVect &v) const {
    cout << "operator+" << endl;
    MyVect result
    return result;
    Then I test it with this very simple code pattern:
    MyVect v1;
    MyVect v2;
    MyVect v3(v1 + v2);
    The output is:
    Constructor
    Constructor
    operator+
    Constructor
    Destructor
    Destructor
    Destructor
    The first two constructor calls are for v1 and v2, then operator+ for  v1+v2 is called, and  inside it there is a constructor call for result object. But then no copy constructor (nor constructor) for v3 is called. In my limited understanding of C++, I guessed that once the temporary object resulting from v1+v2 has been created, then it would be the argument of the copy constructor call. Instead it looks like the compiler transforms the temporary into v3, since v3 is correctly initialized as the sum of v1 and v2 (I tried with a more complicated version of MyVect to verify this). This behavior reminds me of the move semantics introduced with C++11, but I'm not using the -std=c++11 flag (and in fact if I try to define a move constructor the compilation fails).
    Can anyone please help me to understand what's happening under the hood? Thanks.
    Last edited by snack (2013-02-13 10:44:28)

    wikipedia wrote:The following cases may result in a call to a copy constructor:
    When an object is returned by value
    When an object is passed (to a function) by value as an argument
    When an object is thrown
    When an object is caught
    When an object is placed in a brace-enclosed initializer list
    These cases are collectively called copy-initialization and are equivalent to:[2] T x = a;
    It is however, not guaranteed that a copy constructor will be called in these cases, because the C++ Standard allows the compiler to optimize the copy away in certain cases, one example being the return value optimization (sometimes referred to as RVO).
    Last edited by Lord Bo (2013-02-13 13:58:47)

  • Call a constructor as an array

    suppose there is a constructor that takes an argument
    public ball(int radius){
    this.radius=radius;
    now I need to call array of constructor ball(radius). how do i do it?
    thanks

    csckid wrote:
    suppose there is a constructor that takes an argument
    public ball(int radius){
    this.radius=radius;
    now I need to call array of constructor ball(radius). how do i do it?You don't really call the constructor. It gets called when you create an object using new. So to fill an array with ball objects you create the number of objects you need and assign them to the ball array elements.

  • Cannot call parametrized  constructor

    I have a class which extends an abstract class and have the following problem:
    - When i use the default constructor, all works fine
    - When i try to use the 'parametrized' constructor, compile fails....
    Any suggestions, sorry if i oversee any 'elementary coding'....
    calling class
    package testAbstract;
    public class FinalAbstract extends BaseAbstract {
         * Launches this application
        public static void main(String[] args) {
            FinalAbstract myApplication = new FinalAbstract();           // this works
            // FinalAbstract myApplication = new FinalAbstract(true);    // this doesn't
            myApplication.setTitle("AbstractTest");
        public void activateApplication() {
    abstract class
    package testAbstract;
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public abstract class BaseAbstract extends JFrame {
        // Variables
        private static boolean isTestVal = false;
        // Swing objects and varialbles
        private JPanel jContentPane;
         * This is the default constructor
        public BaseAbstract() {
             this(isTestVal);
         * This constructor contains a parameter
        public BaseAbstract(boolean isValue) {
            System.out.print("Executing BaseAbstract(boolean isValue()");
            System.out.print("isValue = " + isValue);
            // Start Application
            initialize();
        public abstract void activateApplication();
        private void initialize() {
            setContentPane(getJContentPane());
            setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
            setTitle("MyBaseAbstractApplication");
            setSize(400,300);
            setVisible(true);
            //Validate
            this.validate();
            //Center the window
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            Dimension frameSize = this.getSize();
            if (frameSize.height > screenSize.height) {
              frameSize.height = screenSize.height;
            if (frameSize.width > screenSize.width) {
              frameSize.width = screenSize.width;
            setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        private JPanel getJContentPane() {
            if (jContentPane == null) {
                jContentPane = new JPanel();
                jContentPane.setLayout(new BorderLayout());
                jContentPane.add(new javax.swing.JLabel("Test"), java.awt.BorderLayout.CENTER);
            return jContentPane;
    }

    Thanks.
    I changed the code as in example which can be compiled now.
    So, i have to declare constructors without any code but with parameters only?
    Can i add some specific code here? If so, which code is executed?
    Now, when executing the code, the parameter is not ported..., the print.out statement shows a value of 'false' whereas i call the constructor with 'true'
    package testAbstract;
    public class FinalAbstract extends BaseAbstract {
         * Launches this application
        public static void main(String[] args) {
            boolean isValue = true;
            // FinalAbstract myApplication1 = new FinalAbstract();           // this works
            FinalAbstract myApplication2 = new FinalAbstract(isValue);    // this doesn't
            // myApplication1.setTitle("AbstractTest without parameter");
            myApplication2.setTitle("AbstractTest with parameter");
        public FinalAbstract(){}
        public FinalAbstract(boolean isValue) {}
        public void activateApplication() {
    }

  • How call the constructor of the super type in the sub type?

    Hi, everybody:
    There are two type as belowing code:
    CREATE TYEP super_t AS OBJECT (
    a NUMBER(7,1),
    b NUMBER(7,1),
    CONSTRUCTOR FUNCTION super_t
    (a IN NUMBER:=null, b IN NUMBER:=null) RETURN SELF AS RESULT
    ) NOT FINAL;
    CREATE TYEP sub_t UNDER super_t (
    CONSTRUCTOR FUNCTION sub_t RETURN SELF AS RESULT
    Because super_t has the constructor that can pass 0 to two parameters, does the constructor of the sub_t can call the constructor of the super_t to create the instance of the sub_t?
    If can, how call?
    If not, need to rewrite the code as the constructor of the super_t in the constructor of the sub_t?
    Thank you very much!

    No the supertype constructor is not automatically called (that should have been trivial for you to prove to yourself). Unfortunately, you can't call it from the subtype either (there is functionality like Java's 'super'). You could define a named method in the supertype that does the initialization and call that in both the constructors however.

  • Why Can't I call a constructor?

    Hello all,
    Why cant i call a constructor as a function?, just like any other function by its name?...
    class Test{
         Test(){
        void func(){
             Test();    // why cant i do this?
    To me it looks just like another function. So whats the wrong in calling it as a function?...

    It says "Method not found" because there is no method Test() in your class, only a constructor with that name (without parameters), as already mentioned by a previous poster. Try to replace the line by new Test(); and it should work. But note that this will create a new object of the class and so, doesn't make any sense.
    Think of constructors being only called when creating a new object. So you don't want "to call the constructor again", because the object already exists.
    Constructors and methods are really something very different. You might have a look at the Java tutorial for further details:
    http://java.sun.com/docs/books/tutorial/java/index.html

  • Calling a constructor

    I have an instantiated class, with the initialization code in the constructor. I want to be able to call the constructor again (to reset object data) without moving the reference to the object. Is there an easy way to do this? I don't want to have to put data initialization into a separate function.

    // Java ain't no C++
    void T::reinit() {
    delete this;
    *this = * ( new T());
    }...and that ain't no C++ either ;-)
    Sorry for the off-topic reply, but that code cannot stand uncorrected.delete this; Only valid for heap-constructed objects, which you can't be sure of inside the function. Will crash otherwise.
    If "this" was in fact on the heap, execution might indeed reach this line:
    *this = * ( new T()); ...only to crash there, since it's an illegal dereferencing of "this", which has just been deleted.
    (Surviving the Access Violation, you'd then have a memory leak, since new T() will never be deleted.)
    The correct C++ way of doing a re-initialization would make use of placement-new.
    void T::reinit()
    T::~T();
    new(this) T();
    }

Maybe you are looking for