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.

Similar Messages

  • 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

  • Af:Table data refresh without calling ManagedBean constructor

    Hi,
    I have an adf application jspx page where I have af:selectOneChoice and af:table showing default data. On selecting af:selectOneChoice value (assigned, completed etc.) I am calling managed bean method which calls task flow client api which gets the task details based on af:selectOneChoice value and show in the adf table.
    When ever I change the af:selectOneChoice value, first it is callling 'valueChanged(ValueChangeEvent valueChangeEvent)' method in managed bean and able to get the records based on filter value(Example: Assigned). Issue is immediatly after that Managed bean constructor also calling which overrides the previous query and get the records based on default filter value (Example: All).
    here is <af:selectOneChoice & <af:table code:
    <af:selectOneChoice id="rsoc" autoSubmit="true"
    binding="#{backingBeanScope.backing_taskdetails.rsoc}"
    label="Status" valueChangeListener="#{backingBeanScope.backing_taskdetails.valueChanged}">
    <f:selectItem itemValue="A" itemLabel="All" />
    <f:selectItem itemValue="AG" itemLabel="Assigned" />
    <f:selectItem itemValue="C" itemLabel="Completed" />
    </af:selectOneChoice>
    <af:table emptyText="#{bindings.taskList.viewable ? 'No data to display.' : 'Access Denied.'}"
    var="row" columnStretching="multiple"
    value="#{backingBeanScope.backing_taskdetails.taskList}"
    immediate="false" rowSelection="single"
    binding="#{backingBeanScope.backing_taskdetails.t1}"
    id="t1"
    inlineStyle="font-family:Arial, Helvetica, sans-serif; border:0pt none; "
    partialTriggers="::rsoc">
    Here partialTriggers is invoking managed bean. So Can I refresh only table data without calling managed bean constructor on selection of <af:selectOneChoice?
    Any inputs will be highly appreciated. Thanks.

    Hi,
    Thanks for your reply.
    here it is my adfc-config.xml file.
    <?xml version="1.0" encoding="UTF-8" ?>
    <adfc-config xmlns="http://xmlns.oracle.com/adf/controller" version="1.2">
    <managed-bean id="__2">
    <managed-bean-name id="__3">backing_test</managed-bean-name>
    <managed-bean-class id="__4">view.backing.Test</managed-bean-class>
    <managed-bean-scope id="__1">backingBean</managed-bean-scope>
    <!--oracle-jdev-comment:managed-bean-jsp-link:1test.jspx-->
    </managed-bean>
    </adfc-config>
    I am not using adf taskflow (Should I use this, I am not sure as I am new to ADF. Please suggest). My execution flow is I have 'Human Task SOA application' which I am calling from adf application (managed bean --> workflow cllient API --> Human Task SOA Application) and showing task details in cutom UI screens. I do not want to use BPM worklist application as I need my own screens.
    thanks.

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

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

  • How to inheritance a super class without no-argument constructor

    i try to inheritance javax.swing.tree.DefaultTreeModel:
    public class myTreeModel extends DefaultTreeModel
    but the compiler say:
    'constructor DefaultTreeModel() not found in class javax.swing.tree.DefaultTreeModel'
    and stoped.
    How can I get around this?
    THANK YOU for your consideration.

    Inside myTreeModel, i tried several things:
    1. add a no-argument constructor;
    Your no argument constructor should be either one of the below :
    public myTreeModel() {
       super(new DefaultMutableTreeNode());
    public myTreeModel() {
       super(new DefaultMutableTreeNode(), true);
    2. add a contructor with (DefaultTreeNode) argument;
    Your constructor with tree node argument should be either one of the below :
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node);
    public myTreeModel(DefaultMutableTreeNode node) {
       super(node, true);
    }You would get an error if you did the following:
    public myTreeModel() {
    public myTreeModel(DefaultMutableTreeNode node) {
    }In both of the cases the default no arguement constructor of the super class is called implicitly like:
    public myTreeModel() {
       super();
    public myTreeModel(DefaultMutableTreeNode node) {
       super();
    }In this case the call super() is refering to a no arguement constructor in DefaultTreeModel. However, no such constructor exists in the DefaultTreeModel class resulting in a compile time error.
    Note: You do not need to use DefaultMutableTreeNode. You an use some other class that implements the TreeNode interface.

  • Sub class   calls super in constructor

    when a sub calss calls super() in its constructor is it overriding the constructor of base class ?
    Class A {
    A(Strin neme){
    class B extend A{
    B(){
    super("test")
    Systemout......
    I donot know the term explaning this feature is it called overriding constructor?

    miro_connect wrote:
    so how to describe this code, are there any terms to explain this methodology to not technical guys ?Yeh. "Magic". Seriously. There's little point explaining such things to non-technical people. Ever tried to teach your mum how to program a VCR?
    By definition, non-tech people will simply not understand what you're on about, and won't need to.

  • 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);

  • Error in calling Super() method cannot reference ...

    import javax.swing.JFrame;
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class MyFrame extends JFrame {
    String St="Rayudu";
         JPanel jp1= new JPanel();
         JButton jb1=new JButton("Hello");     
    public MyFrame() {
    super("Document :" + St);
              jp1.add(jb1);
              getContentPane().add(jp1);
    //...Then set the window size or call pack...
    setSize(300,300);
    //Set the window's location.
         setLocation(300,300);
         setVisible(true);
    public static void main(String ar[])
    MyFrame mf=new MyFrame();
    mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    C:\java>javac My*.java
    MyFrame.java:11: cannot reference St before supertype constructor has been called
    super("Document :" + St);
    ^
    1 error
    Can anyone explain?
    thanks in advance.

    Change your constructor to take an argument of type String, pass this along to the super method when you call the new instance of your class in main. ie:
    public myFrame( String title ) {
    super( "Document: " + title );
    st = title; //if you need it in that String Object assign it here.
    //etc...
    public static void main( String args[] ) {
    new myFrame( "Testing" );
    Does this answer your question?

  • 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 to Call super()

    Suppose I have a class named Class1. Another class extends Class2 which extends Class1.
    class Class1{
    Class1(){
    class Class2 extends Class1{
    Class21(){
    super()//Why this.. Any way, super constructor is being called no??
    We sometimes call super() in the constructor of the sub class to invoke the Super Class constructor. Now, my question is, Whenever we make a new instance of a class, it is any way going to call the super class constructor as per the basic Java design. Then Why, we sometimes call super() specifically.. ???
    Thanx in Advance..
    Naren

    When java calls the super class constructor, it calls the no argument
    constructor.One reason to call the constructor is if the class was
    designed without a no argument constructor. You would get an error
    if you extended it and didn't call its constructor.You may also want to
    call a different constructor instead of the default one.

  • Calling super in subclasses

    Is there a pattern to accomplish the following?
    I have a setup() method that must be called:
    class A {
      public void setup() {
        // necessary code for A
    }I want to ensure its code gets executed even if a subclass overides it. The usual way is with a "hook":
    class A {
      public final void setup() {
        // necessary code for A
        onSetup();
      public void onSetup() {}
    }This way, a subclass can only override onSetup(), ensuring that the code in setup() gets called. However, say I want to play the same trick with subclasses of A:
    class B extends A {
      public final void onSetup() {
        // necessary code for B
        onOnSetup();
      public void onOnSetup() {}
    class C extends B {
      public final void onOnSetup() {
        // necessary code for C
        onOnOnSetup();
      public void onOnOnSetup() {}
    }Is there a pattern I can use so that each class only has to override a method called setup(), and it is guaranteed that the code in every overidden setup() method will be called? Calling super() from within each setup() is fragile, because a subclass might forget it. Using a hook each time (as in the above example) is annoying, because each time, a different name must be assigned to the non-final method at every level in the hierarchy.

    I have dealt with this. In keeping with the principle of not calling overridable methods in constructors, one may require such a method. For instance, I have objects that are ultimately part of a database, but when created they do not have the db object yet. So later they must be setup with the appropriate db object.
    I think it is understood that overriding a method involves respecting the class you are altering. You should not override a method if you do not understand what it does. That being said, the solution here is to simply put in the comment of the method that it must always be called by any subclasses. There are lots of things which can not be forced. If one overrides this method but does not call super, they are violating the contract of the class.
    You can add a private boolean isSetup, and assert if any methods are called before isSetup is true, if you wish. Personally I would throw an IdiotException :-)
    If you have time to burn and want to get buck wild, you can also use the strategy pattern.
    class AClass {
      private List setupers = new ArrayList();
      AClass(){
         Setuper su = new Setuper() {
              public void setup() {
                   //do setup for AClass
          setupers.add(su);
      public final void setup(){
          for(Iterator it = setupers.iterator();it.hasNext();){
             ((Setuper)it.next()).setup();
           setupers = null;
    class BClass extends AClass {
      BClass(){
         Setuper su = new Setuper() {
              public void setup() {
                   //do setup for BClass
          setupers.add(su);
    interface Setuper {
        public void setup();
    }But once you start down this road, you will eventually come face to face with the fact that some things are understood and a certain amount of intelligence, no, respect is required to extend a class properly. There will always be a way to force the issue, but it will involve increasing amonts of work with little pay off. You cant save people from themselves.

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

  • 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

  • IPhone 5s having weird issues...anyone have this too??

    Hello(: So I've had the iPhone 5s ever since the release and around the first week I noticed it randomly restarted itself but everything was working properly so I let it slide by. However, ever since then my phone would freeze on what ever app/screen

  • Can hard disk be replaced with larger capacity of SSD or SATA disk?

    Weighing on buying a Twist, can I replace the hard disk with larger capacity SSD or SATA disk? Is there any capacity limit on SATA disk? Are SSD and SATA disks compatible for Twist (say replace SSD disk with SATA disk or vice versa? Many thanks.

  • Migrating Assets Under Construction?

    Hi all, A customer has many fixed assets that are currently under construction during a Go Live implementation.  I realize ByD uses projects as a bit of a work around for handling assets under construction in the system, but what is the best way to h

  • Apparent "Memory Leak"

    I can't keep Skype loaded without crashing Windows because all memory gets used. Memory usage starts at about 2.6 GB RAM when I load Skype. Then climbs to consume all memory (4 GB ) within 60-90 minutes - even when not on a call.  Issue stops when I

  • Problem in canvas window positioning

    Dear buddies, I'm using Dev-6i....whenever I minimize the MDI window of my forms and then maximize it, the canvas window is resized and moves upward and so its buttons toolbar which I created myself ( and not using built-in Default & Smart Bar) gets