Trying to inherit a super constructor

Lets suppose I have a parent and child.
public class Parent{
public Parent(String string){
//do some stuff here
public class Child{
and finally some other class using the child
pubilc class myChildTester{
pubilc static void main(String[] args){
Child child = new Child("heres a string");
//do some stuff with it
Now i completely understand that this itself wont work, since the child does not have that constructor. What I want to do is to somehow force the child to know enough to use the super constructor. However, I dont want to have to do something fancy like change the java compiler obviously. Also, no code is to be added to the child.
The reason I ask this is because in reality I have a similar situation. In that case though the parent has three different constructors the child needs. However the child only ever uses the "super" constructor, without adding any other functionality. Also, instead of just one child, I have maybe 100 different ones. I dont want to have to copy and paste the constructor that just calls "super" every single time. This is just pure laziness, but I see absolutely no reason why java wouldnt know enough to do this, since it does it already for the default constructor (and even that only works conditionally).
Also, doing something like making another method in the parent (i.e. like a getInstance(String string) method) that the child could use. I must have the constructor, because I'm using Spring to do some stuff on these classes.
I highly doubt there actually IS a way to do anything around this. But any suggestions would be appreciated

and no constructor with a super call.Well, the language is very clear: Constructors are not methods and not inherited.
You have the brittle superclass problem.
One way to handle your situation is to replace the constructors in the parent class with factory methods with the same parameter list as the constructor. In addtion the factory method is supplied information about which child should be created, like
class Parent {
   public static Parent create(ChildType type, T1 p1, T2 p2)  { // factory method
      Parent p = null;
      switch (type) { // create proper child
          Cld1: p = new Child1(); break;
          Cld2: p = new Child2(); break;
          // do the constructors work
      p.setP1(p1);
      p.setP2(p2);
      return p;  
class Child1 extends Parent {
class Child2 extends Parent {
Parent p1 = Parent.create(Cld1, 0, 1);
Parent p2 = Parent.create(Cld2, 1, 0);

Similar Messages

  • Invoking super constructor of a parameterized class

    Hi all,
    I am getting a rather surprising warning messge
    "Type safety: The constructor Super(Class) belongs to the raw type Super. References to the generic type Super<T> should be parameterized."
    Of course, if the super constructor accepts Class instead of Class<T>, then everything is OK.
    I've tried all sorts of things to get rid of this, all to no effect. What to do?
    public class Super<T> {
         public Super(Class<T> c) {
    public class Sub extends Super {
         public Sub(Class<Object> c) {
              // warns on the following line:
              super(c); 
    }Thanks for any help!
    Marc

    Or, if Sub is to be generic:
    public class Sub<T> extends Super<T> {
      public Sub(Class<T> c) {
    }

  • Implicit super constructor is undefined.

    I'm getting this error:
    Implicit super constructor WeightedMeasurement is undefined. Must explicity invoke another constructor.
    WeightedMeasurement is an abstract class in apache.commons.math. So no, it does not have a constructor as such, though it does define 2:
    WeightedMeasurement(double weight, double measuredValue)
    WeightedMeasurement(double weight, double measuredValue, boolean ignored)So I I tried to override like so:
    import org.apache.commons.math.estimation.WeightedMeasurement;
    public class MyWeightedMeasurement extends WeightedMeasurement {
         public MyWeightedMeasurement() {
              String s = new String();
         public MyWeightedMeasurement(double weight, double measuredValue, int x) {
              new MyWeightedMeasurement();
    }but no dice.
    What do I need to do?
    I searched, but didn't find any help.

    I tried the following and it works:
    public abstract class ATestConst
         int computedValue = 0;
         public ATestConst(int val1, int val2)
              computedValue = val1 * val2;
    public class TestingConst extends ATestConst
         int myComputedValue = 0;
         public TestingConst(int v1, int v2, int v3)
              super(v1, v2);
              myComputedValue = super.computedValue / v3;
              System.out.println("My Computed Value: " + myComputedValue);
         public static void main(String[] args)
              int value1 = Integer.parseInt(args[0]);
              int value2 = Integer.parseInt(args[1]);
              int value3 = Integer.parseInt(args[2]);
              new TestingConst(value1, value2, value3);
    }

  • Super() constructor must be first. Is it right?

    My previous discussion abot the this issue has been removed. I must reconstruct it to be aware of advantages, disadvantages and bypasses over the restriction.
    Obvously, the restriction prevents us from writing some perfectly valid code:
    class Unsigned7BitOscillatorInputStream extends OscillatorInputStream {
         Unsigned7BitOscillatorInputStream(
              PeriodicSignal signal,
              float amplitude,
              float signalFrequency,
              AudioFormat f,
              long framesLength)
              // call super substituting the audio format
              super(
                   signal,
                   amplitude,
                   signalFrequency,
                   new AudioFormat(AudioFormat.Encoding.PCM_UNSIGNED,
                        f.getSampleRate(),
                        8, f.getChannels(),
                        f.getFrameSize(),
                        f.getFrameRate(),
                        false
                   framesLength);
         }It is the same if one writes
    class Unsigned7BitOscillatorInputStream extends OscillatorInputStream {
         Unsigned7BitOscillatorInputStream(
              PeriodicSignal signal,
              float amplitude,
              float signalFrequency,
              AudioFormat f,
              long framesLength)
              // create audio format for super class, overriding bps
              AudioFormat format = new AudioFormat(
                   AudioFormat.Encoding.PCM_UNSIGNED,
                   f.getSampleRate(),
                   8,
                   f.getChannels(),
                   f.getFrameSize(),
                   f.getFrameRate(),
                   false);
              super(signal, amplitude, signalFrequency, format, framesLength);
         }Fortunately, the new AudioFormat obect can be created inline with super call. Nevertheless, actually, anyway, the instantiation of the local object preceeds the super call. So what was the reason to prevent java programmers from writing strightforward code, make them decieving themselves and looking for ugly bypasses? What if some comuptation must be done and some fields initialized before super can be called? What if I want to log the arguments passed before calling the super constructor? I wonder how java designers know in which order the fields must be initialized/accessed. IMO, it is exactly constructor's competence.

    Java was specifically constructed with limitations in
    mind based on experience with common problem areas.
    Notice that I said "specifically".Does it mean they all the OOP practices are the best? Should I use them as a reference? Which kind of errors does it protect me from? I would like to see a document telling that calling super constructor is evil, really. Peahaps the reasons lie not in best OOP practice but rather some technical/historical sad fact. It would be amusing if you are defending somenes mistake. I'm sure is java did not initially had the real type (float point) for the reason of its support complexity, the java bigots today would prove that the real numbers are evil and the requirement to use this type in your program points to a flaw in your design. The paramount evidence on the best programming practices will, of course, be the JLS bible. Like they prove there must not be a Set.get(key) in the set class/interface. They tell me that there must be none need to request an object of the same class ("class" in math terms) equivalent to that one you have put into the set. They tell me that if I need the method, my design is flawed. However, actually, the lack of the method in java.collections is nothing more than their designer's mistake. The most obvious illustration are relational tables in DB: the keys are parts (fields, members) of records (entities, objects) while tables are nothing more than sets of objects. Using maps in this case is inappropriate and inferes redundancy. But that's another story... Though the superfirst requirement also adds the extra complexity and must be thoroghly justified. Any artifical overcomlication/redundancy must have a solid evidence. IMO, the objected limitation looks like a 5th wheel in a java-telega.
    I have programmed with gotos many years ago. My experiance proves the Dykstra's (one of the structural programming fathers) thesis stating the "gotos are evil". The gotos break the flow of control making it hard to follow. Therefore, I readitly accept it. I have never seen the thesis, but I'm sure I can find and refer it to you if you like. At the same time, I'm sure there is nothing similiar in OOP domain telling the "deferred" supercons are evil. Otherwise, you would be more specific in references. Suppose, someone confines you into a prison, argumenting this is a "specific tool/limitation" to prevent "some" problems. Will you agree? You will insist on some more serious criminations? Be happy - they tell you - you are allowed to argument against the confinement appealing to our community (the community are the people believing the authority blindly)! No, it is accepted in justice that any limitation of freedom must be justified, not the contrary! This is called a presumption of innocence. I suffer, I break my mind when I know that the following invocations are the same but the second does not work for some queer reason:
              B() {
              super(computePrereq());
         B() {
              r = computePrereq(); // why this is worse than above? Where is the justice?
              super(r);
    I think you can find more than a couple of C++
    best practices books and articles that will tell
    you how C++ constructors should be built.Wow, you refer me to C++ as a citadel for OOP best practices! OK. CPP::STL "package" has the get_by_key method in the Set class/template. Will this fact chagne the mind of java bigots? Obviously not, they immediately refuse your arguments just hearing c++. I can, but just please be more specific. I may to carefully explore a ton of books without finding any sign of super second is evil.
    My favorite lang on Wintel platform is Delphi. Many thoughtful people consider it as a Wintel native java. However, there is even no recommendation to use superconstructors first. And the broad experience suggests me that there is nothing harmful in deferring the superconstruction. I do not feel any nasty frustration similar to exploiting gotos. The super destructors must be called last indeed, since they ultimately call the root superclass's (TObject) destructor, which deallocs the mem and the object ceases to exist after the call. But constructors do not alloc any mem for the object fields, they just fill the fields. The order of initialization is absolutely free. The initialization of all the fields may even be made in parallel for performance.
    Delphi also has a interface-resolution mechanism. Two interfaces conflict when they specify two aliasing methods. Will you tell that it is a bad design if happens that two interfaces conflict? The Divide&Concure disign rule tells the contrary, it is bad design when you must care about other blocks developing one. It is java which has design flaw - you must care about names of methods in other interfaces. This is the experiance collected from wast SW/HW methodologies I can share with java community.
    Show me why I cannot construct a human without
    first
    producing an ape?
    False analogy. I doubt that anyone would ever
    construct an inheritence hierarchy like that.I do not belive in God either ;)
    The evolution took itself.
    Or construct a tree without first
    producing a plant? And that would be logically inconsistent. A tree is
    a plant. If plant does not exist then a tree can not
    either.OK. Which plant should I create before proceeding to construct a tree? Do you understand that the Plant and Tree are the classes while an instance of the Tree just belongs to these classes? The calsses are loaded prior to construction. Now, I'm creating a tree. It is not your matter how the tree is created. You just get a tree and if it is a valid tree; that is, your tree implements all methods of the interface the tree class commits to implement, then it is also a plant. The construction technology is not important. The constructor knows it better when to create a steam and leafs.
    Your analogies are a bit absurd. There are other
    more relevent ones though...
    Employee (parent) -> surpervisor (child).
    Based on your argument it is stupid to have a
    supervisor who is an employee. Whereas in the world
    I live in the vast majority of the time supervisors
    are employees. And in the cases where they aren't
    (rare contractual situations) then building a
    hierarchy that reflects that relationship is a design
    flaw which has nothing to do with construction.Where did I argument against this relatioship? Nevertheless, if it bothers you I can tell you my opinion. In the manager-workers pattern, the emploee (also called a manager) is a job, whos duty consists of finding the workers, hand out a job to them and accepting (supervising) the work done. It may also stimulate/motivate the workers, but that is not important. What's more important is that the surpervision is one of manager's duties. Any Manager is a supervisor by definition. Thus, I can explain why Ape and Human are two different classes in the ancestor-descendant relationship, but I cannot explain you manager-supervisor subclassing... I would establish an Employee class implementing its duty interfaces listed. At least, since multiinheritance is not supported in java and you'll have a problem deriving the Emploee from both task initiator and inspector. If you like.
    The plant appears
    altogether with a tree. Talking in a scientigic
    language, being a plant is nothing more than an
    attribute of a tree (which cannot appearahead of the
    object). They appear simultaneously and are
    indistinguishble as a single whole.You said it not me. If you are using attributes and
    nothing else to construct inheritence then your
    design is flawed.Excuse me for not understanding/appretiating your humor. The "Tree" objects are attributed to "Plants" class. Don't you agree of what?
    To put it bluntly, this is you who seem to use inappropriete terminology. In programming, the parent-children relationship is used for tree structures (has-a). Parent may have (or own) a set of children. However, no parent construction precedes the construction of every "child" object. Otherwise, we would get too many parents. While we need descedants. The descedants have attributes of parents but they are not separate objects. Like keyfields in a DB records. All the fields are equal (if we do not toudch the pragmatic level). The ancestor-descendant terminology is adoped in OOP (the talks about inheritance). In java, super/sub-class notation is accustomed. This sharpens my confusion on which "parents" should I create before initializing any new object specific fields.
    Looks like a demagogic sentence. Let's think of a
    human as a brain-increased ape without tail. Do
    again?) or proceeded directly?
    Again you are using a very bad example for
    inheritence.I fail to see why the natural exapmles of inheritance are somehow "bad". OK, not all apes are brain-low, since humen break this rule.
    No, but I can make a soudspeaker without bringingits
    "parent" (presumably, a soundsystem) into "a valid
    state". I can write a java program withoutbringing
    some "abstract" program into a valid state.
    Even worse example. A "sound system" is a
    collection of other objects.
    There is no way that a speaker is ever a child or a
    parent of an amplifier.Thereofore, an abstract soundsystem may not have any concrete descendants? A soundsystem consumes a stream of databits or continous electric signal and produces sound waves. A laudspeaker near to me is full of controls - volume, bass, ets.. What is it if not an incarnation of a sound system?
    OK, here is another example. A floppy-disk is a disk. Should one produce a disk before making it floppy? Or microwave owen is an owen. How do you think should I create an owen prior to making it a microwave? Or electric field, how do I create a field prior to adding the electric parameters? Or how do I construct a hammer if you require me to precede its construction by construction of abstract instrument? How do I manufacturers produce "parent" computers before attaching "personal" properties to it? I'm sure there are millions of ways to construct a PC but none of them requires producing some "parent".
    OK, which chapter of CS tells that "parents" mustbe
    created prior to a "children"? Should Intel start
    manufacturning their Pentium chips by producing8088
    core first? I am beginning to think that you have a substantially
    different view than most people about what
    inheritence means.
    I find it hard to believe that anyone, in any
    situation, would ever attempt to create an
    inheritence tree using 8080 as the parent and a
    pentium as the child. This is a historical
    relationship not a child parent one.The Pentioum extends functionality of 8088 (both HW and SW). Engeneers started more and more features at the core. Finally they got a huge monster. It still starts as 8088. A program can call for extended capabilities if it knows about them. The old programs work on Pentium using its 8088 inherited interface.
    What do you mean telling "parent in valid
    state"? In construction, only ONE object isproduced,
    which complies to its ancestor interface.
    Constructors just aid the process. May be youwanted
    to tell there is no analogy between OOP and the
    nature?A tree is a plant. It is nonsense to suggest that a
    tree can exist before plant exists.As I have told, I have never suggested for such a nonsense. The Plant class exits long before you create an instance of a tree.
    That has nothing to do with the relationship between
    an acorn and an oak however. Nor does the fact that
    an oak produces acorns mean that there is a child
    parent relationship in terms of OO in there.I have never told that the seeds are plants. Moreover, I do not see any relation here with your proir argument that the creation of instance of an oak must be preceeded by the creation of instantance of some abstract plant (belonging to a Plant class) and the tree instance constructor then must decorate the the basic structure of that plant instance.
    Please refer me to a book telling that fields of superclass must be initialized prior to (not after and not concurrently) with the new fields exposed by a subclass.

  • Catching exception of a super constructor

    Is it possible to catch the exception thrown by a super class
    constructor in a sub clas constructor?
    public class A
         public A() throws Exception
              throw new Exception("Exception from A");
    class B extends A
         public B()
              try
                   super();
              catch(Exception e)
    }I get an error saying,
    A.java:16: call to super must be first statement in constructor
    super();
    ^
    Any thoughts?

    More on this here,
    http://archive.devx.com/free/tips/tipview.asp?content_i
    =2384&Java=ONThanks for that link. I completely agree to what it says.
    In other words, not being able to successfully construct our super class implies that we cannot create our derived class.
    But I feel this must be mentioned clearly somewhere in JLS. And the error message that we get must be "You cannot catch exceptions thrown by a super class constructor".

  • Extending object, without calling super constructor

    public class Object1
        byte index;
        public Object1(byte i)
            index = i;
    public class Object2 extends Object1
        private byte j;
        public Object2() {
            super((byte) 0);
        public void setIndex(byte i)
            j = i;
    import java.util.*;
    public class Test1
        private ArrayList<Object1> aList;
        public Test1()
            aList = new ArrayList<Object1>();
        public void run()
            for (byte i = 0; i < 10; i++)
                aList.add(new Object1(i));
        public ArrayList<Object1> getResults()
            return aList;
    import java.util.*;
    public class Test2
        ArrayList<Object1> results;
         * Constructor for objects of class Test2
        public Test2()
            Test1 t1 = new Test1();
            t1.run();
            results = t1.getResults();
        public void run()
            Iterator<Object1> i = results.iterator();
            while (i.hasNext())
                Object2 o2 = (Object2) i.next();
    public class Test3
        public static void main(String[] args)
            Test2 t2 = new Test2();
            t2.run();
    }There are two things with this code that I'm having problems with.
    1. I want to create an object of class Object1 in Test1. That works fine. In Test2 I then want to extract the object from the ArrayList, but since Object2 extends Object1, I want to get an Object2 out from the ArrayList. However with the code above, I get a ClassCastException. If I leave out the cast, I get an incompatible types error.
    2. I want Object2 to be an extension of Object1, that is, with more fields and methods. But I have no need to create an object of class Object2, since I know I already have an ArrayList of Object1. So I want to remove the constructor from Object2, seeing as I won't need it. However, if I remove the super part (which, again, is not needed, as I will already have created my needed objects of class Object1 when I get there, and only need to EXTEND my Object1 objects), I get a cannot find symbol, constructor Object1() error.
    I'm not sure that I can solve problem 2 without using a super. But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.

    ThemePark wrote:
    But I am convinced that I must be able to get the Object1 objects out as Object2 instead. I would just like some help with how to do that.Maybe you don't understand how inheritance works. Go read a basic tutorial on inheritance. You can use an Object2 as an Object1, but not an Object1 as an Object2. You either have to create Object2 objects in the first place; or have to make a wrapper class that takes an Object1 and passes things to the Object1 object; and use objects of this wrapper class.

  • Trying to find a super computer for premier pro where do I go?

    Can anyone tell me where to find a super computer for our windows based premier pro>

    If you know what you are doing and can build one yourself then go with Jim's suggestion
    If you don't then we need to know where you are, presumably you are in the USA and a video system builder may be close at hand
    Alternately contact DVC in the UK
    Col

  • Can defualt inherited the Super Class constructor to sub class ?

    Hi,
    is it passible to inherit the super class constructor by defualt when extends the super class.
    Thanks
    MerlinRoshina

    Constructor rules:
    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.

  • Effect of super() in JDialog constructor on focusability/modality

    Hello again,
    this is a JFrame which calls a JDialog which calls a JDialog.
    Using super(...) in the constructor of SecondDialog makes this dialog
    unfocusable as long as FirstDialog is shown. Without super(...) one can freely
    move between the dialogs.
    Can somebody exlain what "super" does to produce this difference?
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SuperConstructor extends JFrame {
      public SuperConstructor() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(300,300);
        setTitle("Super constructor");
        Container cp= getContentPane();
        JButton b= new JButton("Show dialog");
        b.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent evt) {
         new FirstDialog(SuperConstructor.this);
        cp.add(b, BorderLayout.SOUTH);
        setVisible(true);
      public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
         new SuperConstructor();
      class FirstDialog extends JDialog {
        public FirstDialog(final Frame parent) {
          super(parent, "FirstDialog");
          setSize(200,200);
          setLocationRelativeTo(parent);
          setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
          JButton bNext= new JButton("Show next dialog");
          bNext.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           new SecondDialog(parent, false);
          add(bNext, BorderLayout.SOUTH);
          setVisible(true);
      int i;
      class SecondDialog extends JDialog {
        public SecondDialog(Frame parent, boolean modal) {
          super(parent); // Makes this dialog unfocusable as long as FirstDialog is 
    shown
          setSize(200,200);
          setLocation(300,50);
          setModal(modal);
          setTitle("SecondDialog "+(++i));
          JButton bClose= new JButton("Close");
          bClose.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
           dispose();
          add(bClose, BorderLayout.SOUTH);
          setVisible(true);
    }

    nice day,
    there are three areas of get potential problem
    1/ FirstDialog helt pernament MODALITY, SecondDialog to have to same ...
    2/ there isn't something about change Window focus (if Parent inside of EDT, then you alyway lost focus, meaning SecondDialog)
    3/ constructor super inside class doesn't works, block move focus to the SecondDialog (and nonModal)
    ... but
    4/ here is second coins_side [http://forums.sun.com/thread.jspa?messageID=11020377#11020377]
    5/ in this form is my example returns similair result, isn't possible setWindow focus for visible JDialog (sure, remove Extend JDialog and create separate constuctor for JDialog, solve that)
    6/ maybe I'm wrong
    package JDialog;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    * Parent Modal Dialog. When in modal mode, this dialog
    * will block inputs to the "parent Window" but will
    * allow events to other components
    * @see javax.swing.JDialog
    public class PMDialog extends JDialog {
        private static final long serialVersionUID = 1L;
        private boolean modal = false;
        private WindowAdapter parentWindowListener;
        private Window owner;
        private JFrame blockedFrame = new JFrame("No blocked frame");
        private JFrame noBlockedFrame = new JFrame("Blocked Frame");
        public PMDialog() {
            noBlockedFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            noBlockedFrame.getContentPane().add(new JButton(new AbstractAction("Test button") {
                private static final long serialVersionUID = 1L;
                @Override
                public void actionPerformed(ActionEvent evt) {
                    System.out.println("Non blocked button pushed");
                    /*if (blockedFrame.isVisible()) {
                        noBlockedFrame.setVisible(false);
                    } else {
                        blockedFrame.setVisible(true);
                    noBlockedFrame.setVisible(true);
                    blockedFrame.setVisible(true);
            noBlockedFrame.setSize(200, 200);
            noBlockedFrame.setVisible(true);
            blockedFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
            blockedFrame.getContentPane().add(new JButton(new AbstractAction("Test Button") {
                private static final long serialVersionUID = 1L;
                @Override
                public void actionPerformed(ActionEvent evt) {
                    final PMDialog pmd = new PMDialog(blockedFrame, "Partial Modal Dialog", true);
                    pmd.setSize(200, 100);
                    pmd.setLocationRelativeTo(blockedFrame);
                    pmd.getContentPane().add(new JButton(new AbstractAction("Test button") {
                        private static final long serialVersionUID = 1L;
                        @Override
                        public void actionPerformed(ActionEvent evt) {
                            System.out.println("Blocked button pushed");
                            pmd.setVisible(false);
                            blockedFrame.setVisible(false);
                            noBlockedFrame.setVisible(true);
                    pmd.setDefaultCloseOperation(PMDialog.DISPOSE_ON_CLOSE);
                    pmd.setVisible(true);
                    System.out.println("Returned from Dialog");
            blockedFrame.setSize(200, 200);
            blockedFrame.setLocation(300, 0);
            blockedFrame.setVisible(false);
        public PMDialog(JDialog parent, String title, boolean isModal) {
            super(parent, title, false);
            initDialog(parent, title, isModal);
        public PMDialog(JFrame parent, String title, boolean isModal) {
            super(parent, title, false);
            initDialog(parent, title, isModal);
        private void initDialog(Window parent, String title, boolean isModal) {
            owner = parent;
            modal = isModal;
            parentWindowListener = new WindowAdapter() {
                @Override
                public void windowActivated(WindowEvent e) {
                    if (isVisible()) {
                        System.out.println("Dialog.getFocusBack()");
                        getFocusBack();
        private void getFocusBack() {
            Toolkit.getDefaultToolkit().beep();
            super.setVisible(false);
            super.pack();
            super.setLocationRelativeTo(owner);
            super.setVisible(true);
            //super.toFront();
        @Override
        public void dispose() {
            owner.setEnabled(true);
            owner.setFocusableWindowState(true);
            super.dispose();
        @Override
        @SuppressWarnings("deprecation")
        public void hide() {
            owner.setEnabled(true);
            owner.setFocusableWindowState(true);
            super.hide();
        @Override
        public void setVisible(boolean visible) {
            boolean blockParent = (visible && modal);
            owner.setEnabled(!blockParent);
            owner.setFocusableWindowState(!blockParent);
            super.setVisible(visible);
            if (blockParent) {
                System.out.println("Adding listener to parent ...");
                owner.addWindowListener(parentWindowListener);
                try {
                    if (SwingUtilities.isEventDispatchThread()) {
                        System.out.println("EventDispatchThread");
                        EventQueue theQueue = getToolkit().getSystemEventQueue();
                        while (isVisible()) {
                            AWTEvent event = theQueue.getNextEvent();
                            Object src = event.getSource();
                            if (event instanceof ActiveEvent) {
                                ((ActiveEvent) event).dispatch();
                            } else if (src instanceof Component) {
                                ((Component) src).dispatchEvent(event);
                    } else {
                        System.out.println("OUTSIDE EventDispatchThread");
                        synchronized (getTreeLock()) {
                            while (isVisible()) {
                                try {
                                    getTreeLock().wait();
                                } catch (InterruptedException e) {
                                    break;
                } catch (Exception ex) {
                    ex.printStackTrace();
                    System.out.println("Error from EDT ... : " + ex);
            } else {
                System.out.println("Removing listener from parent ...");
                owner.removeWindowListener(parentWindowListener);
                owner.setEnabled(true);
                owner.setFocusableWindowState(true);
        @Override
        public void setModal(boolean modal) {
            this.modal = modal;
        public static void main(String args[]) {
            PMDialog pMDialog = new PMDialog();
    }

  • Invoked super class constructor means create an object of it?

    Hei,
    i have create one class that extends another class. when i am creating an object of sub class it invoked the constructor of the super class. thats okay.
    but my question is :
    constructor is invoked when class is intitiated means when we create an
    object of sub class it automatically create an object of super class. so means every time it create super class object.

    Hi,
       An object has the fields of its own class plus all fields of its parent class, grandparent class, all the way up to the root class Object. It's necessary to initialize all fields, therefore all constructors must be called! The Java compiler automatically inserts the necessary constructor calls in the process of constructor chaining, or you can do it explicitly.
       The Java compiler inserts a call to the parent constructor (super) if you don't have a constructor call as the first statement of you constructor.
    Normally, you won't need to call the constructor for your parent class because it's automatically generated, but there are two cases where this is necessary.
       1. You want to call a parent constructor which has parameters (the automatically generated super constructor call has no parameters).
       2. There is no parameterless parent constructor because only constructors with parameters are defined in the parent class.
       I hope your query is resolved. If not please let me know.
    Thanks & Regards,
    Charan.

  • Trying to unlock the oid super user

    Hi,
    We are trying to unclock the super user , But forget the passwd, how can we set the passwd, if we have forget.
    oidpasswd connect=asdb unlock_su_acct=true
    It is asking the OID passwd, But we have forget.
    Please help us to resolve the same.
    Regards

    oidpasswd connect=asdb unlock_su_acct=true
    OID DB user password: It asks for OID DB password.
    The ODS password to authenticate to the database must be provided when prompted. The default ODS password (i.e. the password of the ODS schema) is the same as that for the Oracle Application Server administrator entered during installation (i.e. the same password that was assigned to PORTAL, IAS_ADMIN, orcladmin).

  • JUnit test fixture where constructor of base object throws exception

    I'm trying to construct a test case which requires an object whose constructor currently throws and exception (it tries to make a connection which isn't currently available).
    Now normally the trick would be to construct a test fixture class which extends the base class and returns the stuff I want. The trouble is I can't cope with an exception in in super constructor. Is there any way out of this, short of refactoring the offending base class?

    Just use the no-arg constructor of RootRenderingContext, and all should be defaulted appropriately.

  • Easy One: Constructor of Child Classes

    Hello. I am new to the java language and i have a question.
    I want to make a Class Vehicle which should have the following variables
    static int id;
    static long color;
    static String brand;
    static Boolean rented;
    static String location;
    Now i want to make a Child class called 'Car' which should have the .location set to "land" by default.
    I want to also make a Child class of 'Car' called 'Bus' .
    Now the problem is with the constructors. I want that when i create a class Bus that the .location is set to "land" automatically and not with user input. This means it will call the constructor of 'Car' and not 'Vehicle' which sets .location to "land"
    I tried to do so but it tells me 'Constructor Car() was not found' .
    I want the constructor of Car define the .location="land" but the constructor of Bus will not have the .location argument because
    it is set to "land" by default?
    Please help !
    thanks
    code follows:
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Vehicle {
    static int id;
    static long color;
    static String brand;
    static Boolean rented;
    static String location;
    public Vehicle(int myid,long mycolor,String mybrand,Boolean isrented,String mylocation) {
    this.id=myid;
    this.color=mycolor;
    this.brand=mybrand;
    this.rented=isrented;
    this.location=mylocation;
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Car extends Vehicle {
    public Car(int myid,long mycolor,String mybrand,Boolean isrented) {
    super(myid,mycolor,mybrand,isrented,"land");
    package map_exercise;
    * Title:
    * Description:
    * Copyright: Copyright (c) 2003
    * Company:
    * @author
    * @version 1.0
    public class Bus extends Car {
    public Bus(int myid,long mycolor,String mybrand,Boolean isrented) {
    }

    I agree with NadjaS about the general remarks on the use of static vs. instance variables.
    Anyway, if you really need to keep the variables at the class definition level, you can initialize them through the static initializer constructor within the "Car" class itself, i.e. something like this:
    public class Car extends Vehicle {
        static {
            location = "land";
    }without necessarily calling the super constructor.
    The message "Constructor Car() was not found" is due to the fact the the only Car class constructor has four parameters - hence a completely different signature - and there is no constructor without parameters at all.
    Hope this will help.
    Bye

  • Cannot reference this before supertype constructor has been called

    I'm confused. I would like it easier for a user to use a class where one item can be determined from another, but I'm having a problem with the constructors.
    First, one constructor that works fine:
        public UndirectedGraph(List nodes, List edges) {
            this(nodes, edges, 100, 100, true, false);
        }which then calls the ultimate constructor that accepts all those other parameters.
    The problem is with this one:
        public UndirectedGraph(List nodes) {
            this(nodes, collectEdges(nodes), 100, 100, true, false);
        }collectEdges returns a List of Edges, so technically all should be fine. However, this won't compile, with the message:
    UndirectedGraph.java [37:1] cannot reference this before supertype constructor has been called
            this(nodes, collectEdges(nodes));
                               ^
    1 error
    Errors compiling UndirectedGraph.Is there a workaround for what I'm trying to do? It'd be a lot easier to have this collectEdges() method in this single place than in any class that's using this one.

    You HAVE to call the super constructor before you do anything else in the constructor. You can make calls to this but the final constructor to be executed has to make the super call. I am assuming you are subclassing something here because this should not show up as an error if there is a default constuctor. The reson for this is that a subclass is built on top of its parent classes meaning it can access information in them methods in them etc. Even in the constrcutor it can do this so the super class MUST be created before the subclass.

  • Throw difference exception in constructor

    Have a base class constructor that throws an exception of class XException
    Have an exception class YException that inherit exception XException
    If I inherit the base class, can I make it throw exception Y instead of X, since Y is a subclass of exception X?
    Example:
    public class Base {
    public Base() throws XException {
    public class XException extends Exception {
    public XException() {
    // etc...
    public YException extends XException {
    YException() {
    super();
    public MyClass extends Base {
    // Can this work in a constructor since YException is a subclass of XException?
    // Anyway to make this possible?
    public MyClass() throws YException {
    super();

    Have a base class constructor that throws an exception
    of class XException
    Have an exception class YException that inherit
    exception XException
    If I inherit the base class, can I make it throw
    exception Y instead of X, since Y is a subclass of
    exception X?
    Example:
    public class Base {
    public Base() throws XException {
    public class XException extends Exception {
    public XException() {
    // etc...
    public YException extends XException {
    YException() {
    super();
    public MyClass extends Base {
    // Can this work in a constructor since YException is
    a subclass of XException?
    // Anyway to make this possible?
    public MyClass() throws YException {
    super();
    Apart from what you are asking in normal circumstances a no args constructor throwing an exception is never a good idea. The reason being that from then on anybody who extends this class would have to face problems. Consider the following
    public class MyTest
          public MyTest() throws Exception
    class Test extends MyTest
    {}this would not compile and throw the following error
    Default constructor cannot handle exception type Exception thrown by implicit super constructor. Must define an explicit constructor     
    So thats not a good practice
    cheers

Maybe you are looking for