Regarding this or super call in constructors

a call to this or super should be the first line of any constructor if we are providing them?Why cant we have them anywhere in our constructor code?

You can do this using byte code. (not advised!!)
However if you feel you want to move this() or super() there is another way to do what you have in mind.
One thing you can do is call static method in the this/super line which means you can execute code before this/super is called.

Similar Messages

  • This() and super() invocations in constructor bodies

    Hi,
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructor (which in turn implies that
    this() and super() can not be used together) ?
    Also, If the constructor is a constructor for an enum type, it is a compile-time
    error for it to invoke the superclass constructor explicitly. Why ?
    And the last question - why it is not allowed to invoke this() or super()
    with instance fields ?
    Cheers,
    Adrian

    AdrianSosialik wrote:
    Could someone please explain why it is not allowed to explicitly
    call this() or super() in a constructor body anywhere as opposed
    to the first statement in the constructorI think it was a language design decision. One could allow certain statements before invoking another constructor, but this would probably cause more confusion than help. So I guess it was deliberatly chosen to not allow this.
    (which in turn implies that this() and super() can not be used
    together) ?Yes, but if this would be permitted, it would also be harder to guarantee that a superclass constructor gets called exactly once.
    Also, If the constructor is a constructor for an enum type,
    it is a compile-time error for it to invoke the superclass
    constructor explicitly. Why ?Could you provide a "compilable" code snippet that demonstrates this?
    And the last question - why it is not allowed to invoke this()
    or super() with instance fields ?As you are not able to store something in them before the invocation, they contain their default values... (the JVM allows storing values in instance fields before invoking another constructor, but it was apparently decided to not include such a thing in Java)

  • Enable the "calling WebIDL constructors as functions" on the web

    Hi,
    I am developing a web application using php and python. After updating the Firefox to the latest version 30.0, some functions on my app do not work anymore. I checked the change logs of Firefox and found out this change: "Disallow calling WebIDL constructors as functions on the web" caused the issue on my tool.
    So how can I fix this on the browser side since I cannot change the codes immediately right now?
    Also a suggestion: Please reverse this change on the next update of this browser since this will affect my users or else I have to greatly change the codes.
    Thanks

    Please check out where this is fixed and the Site Compatibility list in the last portion of the bug [https://bugzilla.mozilla.org/show_bug.cgi?id=916644]

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

  • 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

  • Super class default constructor

    Hello,
    I want to clear some confusion. I am studying for the exam. In this particular book an example shows that
    Super class has 2 constructor
    public abc() and public abc(int n)
    Sub class has 2 constructor
    public xyz() and public xyz(int n)
    now when an instance is created for the subclass
    xyz t = new xyz(1)
    It will invoke the super class no argument constructor eventhough a default constructor exist in subclass?
    Regards,
    adil

    Here are the rules for constructors--"ctors" because I'm lazy. Also, because I'm lazy, "super(...)" and "this(...)" mean any super or this call, regardless of how many args it takes, including those that take no args.
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • De-serialization not calling default constructor ??

    Hi,
    I have a strange problem with serialization (de-serialization, actually):
    I have a bunch of classes that represent the model for my application.
    These classes are organized as a complex tree and come in three flavors:
    public abstract class AbstractIOCLeaf implements IOCElement {
         private String name;
         private transient boolean changed = false;
         private transient LinkedList<ChangeListener> changeListeners;
         protected AbstractIOCLeaf() {
              super();
              name = null;
              changed = false;
              changeListeners = new LinkedList<ChangeListener>();
         } //needed for Serialzation
         protected AbstractIOCLeaf(String name) {
              this();
              this.name = name;
    ...this class is a leaf: it cannot contain other sub-elements.
    public abstract class AbstractIOCList<T extends IOCElement> extends AbstractIOCNode implements ComboBoxModel {
         protected LinkedList<T> list = null;
         protected transient List<ListDataListener> listListeners;
         protected abstract T newElement(String name);     
         protected AbstractIOCList() { super();  listListeners = new LinkedList<ListDataListener>(); }
         public AbstractIOCList(String name) {
              super(name);
              list = new LinkedList<T>();
              listListeners = new LinkedList<ListDataListener>();
    ... This class holds a list of elements that are all equal.
    and finally:
    public abstract class AbstractIOCNode extends AbstractIOCLeaf implements ChangeListener, ListDataListener {
         protected AbstractIOCNode() { super(); }
         protected AbstractIOCNode(String name) {
              super(name);
    ... This class holds elements that are all different.
    The actual classes extends one of these following the pattern:
    public class StateMachine extends AbstractIOCNode {
         private StateList states = null;;
         private EventQueue fEventQueue = null;
         private StateMachine() { super(); }
         private StateMachine(String name) {
              super(name);
              states = StateList.newInstance(this);
              changed = false;
         public static StateMachine newInstance(String name) {
              StateMachine sm = new StateMachine(name);
              sm.initialize();
              return sm;
    public class StateList extends AbstractIOCList<State> {
         private StateMachine sm;
         private StateList() { super("StateList"); sm = null; }
         private StateList(StateMachine sm) {
              this();
              this.sm = sm;
         public static StateList newInstance(StateMachine sm) {
              StateList list = new StateList(sm);
              list.initialize();
              return list;
    ...etc. etc.
    I do serialization calling ObjectOutputStream.writeObject on the root object and (obviously) deserialize using ObjectOutputStream.readObject.
    The process works, but it seems that the default constructors in particular AbstractIOCLeaf() is never called while deserializing. First hint to something amiss was the fact that I always had the transient field changeListeners remaining in its default null state.
    Further investigation involving debugging and breakpointing confirmed no default constructor is called in spite of the super(); calls.
    What am I doing wrong??
    Did I miss something about serialization (apparently so, but I cannot understand what!)?
    Side issue:
    I tried substituting ObjectOutputStream.writeObject with XMLEncoder.writeObject, but then I get the error: "Class sun.reflect.misc.Trampoline can not access a member of class com.softin.IOCbuilder.model.IOController with modifiers "private"".
    Aren't those classes supposed to be equivalent?
    Is there any (fast) way to desume the offending member?
    Excuse me for the length of the post and
    Thanks in Advance
    Mauro

    Oops, nevermind. Sorry.

  • Problem with super() call

    The following code is makin my compiler give me the error:
    Error: super() method calls only allowed in constructors
    Why is that happening? and what to fix it?
    Thanks
    //...some code
    public ProcessaArquivoOFCImpl(File arquivoentrada) throws RemoteException{//M�todo construtor
        //Preparando o registro do objeto
        String serverObjectName = "//localhost/OFCServer";
        try{
          Naming.rebind(serverObjectName, this);
        }catch(MalformedURLException Erro_URL){
          System.out.println("Erro na url de exporta��o");
        //Chama o construtor da superclasse (UnicastRemoteObject)
        super();
        ProcessaArquivoOFC(arquivoentrada);
      public void ProcessaArquivoOFC(File arquivoentrada){
    //...some more code

    To make the mothods be exported. Shouldnt that be done before? If not... can i put it after the super() call?Sure -- no clients need access to it until it's fully initialized, that should probably be the last thing you do.

  • The use of "super" in a constructor

    Hi,
    I am wondering what using "super();" in a constructor does. I've seen this used in may other people's code and I simply don't understand what that line would do.
    Thanks for your advice.

    the super class being that class which you have derived from.
    Example:
    Base Class
    public class Amphibian
    Amphibian();
    System.out.println("Constructor of Amphibian");
    public swims()
    //swim
    <b>SubClass</b>
    public class Frog extends Amphibian
    Frog()
    super(); // this calls constructor of Amphibian and will print out: Constructor of Amphibian to the console
    I hope this helps

  • 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

  • I am sonu v s from india...i am a apple id user...now i have a problem regarding this apple ID...i forget my apple ID security Qn...so i can't access and purchase any apps by using my apple ID..4 tms i frwd my reqst using itune apps store bt no solutn

    I am sonu v s from india...i am a apple id user...now i have a problem regarding this apple ID...i forget my apple ID security question...so i can't access and purchase any apps by using my apple ID..4 times i frwd my reqst using itune apps store but i can't get any solution....many times i my try to call u bt there is no response from ur custmr support group...pls kindly give me any solution

    Contact the App store for Apple ID help. Their support link is on the right of the App store window
    LN

  • How to call parent constructor from subtype body ?

    create or replace TYPE person as object(
    p_name varchar2(10),
    p_age NUMBER,
    p_status CHAR,
    p_addr addr_type,
    constructor function person ( p_name char, p_age NUMBER, p_status CHAR, p_addr addr_type ) RETURN SELF AS RESULT
    )NOT FINAL;
    -- subclass
    create or replace TYPE employee under person(
    e_number number,
    hire_date date,
    e_designation varchar2(15),
    constructor function employee ( e_name char, e_age NUMBER, e_status CHAR,
    e_addr addr_type, e_number NUMBER, hire_date date, e_designation CHAR )
    return SELF AS RESULT
    In this scenario how do we call parent constructor from employee type ?

    Can't You write complete example? Tried few variants but get nothing:(

  • 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() {
    }

  • 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

Maybe you are looking for

  • MacBook Pro Cannot Connect to Wireless Router

    I have a brand new MBP and it won't connect to any non-apple wireless routers - my computer is 2 days old (it's awesome and I love it accept that I can't get wireless connection at home) - wireless router: westell versalink model 327 W - PROBLEM: my

  • Run-time error in alv

    Hi guys, I am executing an alv grid report.i m getting a run time error and i m gettig a dump.In the below i pasted the error.any suggestions where i m going wrong in the code. What happened?                                                          

  • Having issues linking spry menu bar to my other pages

    Hey everyone, I am brand new to web development. I am currently using the trial of DW and I must say I love it. I am having issues with my spry menu bar though. I will click on a certain box in the menu bar and use the properties page at the bottom a

  • Photo in are not in the net-cloud

    my photos, uploaded from i-photo to the cloud, are not in the net-cloud, i call up with safari. when i´m on trip with my old macbook-snow leopard- i´ve no posibility to show. At home-mac book pro- only in i-photo it shows a cloud storage with picture

  • Problem installing Java EE 6 windows.

    I have downloaded the Java EE 6 SDK windows installer. I find that it progresses to about 40% or 75%, but then refuses to progress any further. I have Windows 7 64 bit. What do I do to find an installer for 64 bit Windows and 64 bit Linux that will f