Constructors in Inheritance.

Hi,
REPORT  Z_INHERITANCE_CONSTRUCTOR.
CLASS demo DEFINITION.
  PUBLIC SECTION.
  CLASS-METHODS main.
  ENDCLASS.
CLASS vessel DEFINITION.
  PUBLIC SECTION.
  METHODS : constructor IMPORTING i1 TYPE string
                                                            i2  TYPE string,
                     show_output.
  PROTECTED SECTION.
  DATA name TYPE string.
  DATA *** TYPE string.
  ENDCLASS.
CLASS ship DEFINITION INHERITING FROM vessel.
  ENDCLASS.
CLASS motorship DEFINITION INHERITING FROM ship.
  PUBLIC SECTION.
  METHODS : constructor IMPORTING i_name TYPE string
                                                            i_fuel_amount TYPE i.
  PRIVATE SECTION.
  DATA fuel_amount TYPE i.
  ENDCLASS.
CLASS vessel IMPLEMENTATION.
  METHOD constructor .
    name = i1.
    *** =  i2.
  ENDMETHOD. "constructor
  METHOD show_output .
     DATA : name TYPE string,
                 *** TYPE string,
                 output type string.
                name = me->name.
                *** = me->***.
     CONCATENATE 'The Name is : ' name '& The *** is :' ***  into output.
     MESSAGE output TYPE 'I'.
  ENDMETHOD. "show_output
  ENDCLASS.
CLASS motorship IMPLEMENTATION.
  METHOD constructor .
  super->constructor( i1 = 'Abhinab' i2 = 'M' ).
  fuel_amount = i_fuel_amount.
  ENDMETHOD. "constructor
  ENDCLASS.
CLASS demo IMPLEMENTATION.
  METHOD main .
DATA : o_vessel TYPE REF TO vessel,
        o_ship TYPE REF TO ship,
        o_motorship TYPE REF TO motorship.
CREATE OBJECT : o_vessel EXPORTING i1 = 'Vivien'
                                                                    i2 = 'M',
                                o_ship EXPORTING i1 = 'Sia'
                                                                i2 = 'F',
                                o_motorship EXPORTING i_fuel_amount = '1200'
                                                                          i_name = 'Eules'.
  ENDMETHOD. "main
  ENDCLASS.
  START-OF-SELECTION.
  demo=>main( ).
In my code the method show_output doesn't get implemented,but when i place the same code of show_output  in the constructor method the code is getting executed.
I am not able to figure out the reason behind this.
can anybody please help me understand why is this happening??
Regards,
Abhinab Mishra

The show_output method was never been called.
o_vessel->show_output is required in the main method of demo.
Silly Mistake.
Regards,
Abhinab Mishra

Similar Messages

  • Constructors and Inheritance in Java

    Hi there,
    I'm going over access modifiers in Java from this website and noticed that the following output is displayed if you run the snippet of code.
    Cookie Class
    import javax.swing.*;
    public class Cookie {
         public Cookie() {
              System.out.println("Cookie constructor");
         protected void foo() {
              System.out.println("foo");
    }ChocolateChip class
    public class ChocolateChip extends Cookie {
         public ChocolateChip() {
              System.out.println("ChocolateChip constructor");
         public static void main(String[] args) {
              ChocolateChip x = new ChocolateChip();
              x.foo();
    }Output:
    Cookie constructor
    ChocolateChip constructor
    fooI've been told that constructors are never inherited in Java, so why is "Cookie constructor" still in the output? I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?
    If you can shed any light on this, I would greatly appreciate it.
    Many thanks!

    896602 wrote:
    I've been told that constructors are never inherited in JavaThat is correct. If they were inherited, that would mean that, just by virtue of Cookie having a c'tor with some particular signature, ChocoChip would also "automatically" have a c'tor with that same signature. However, that is not the case.
    , so why is "Cookie constructor" still in the outputBecause invoking a constructor always invokes the parent class's c'tor before any of our own c'tor's body executes, unless the first statement is this(...), to invoke some other c'tor of ours. If this is the case, eventually down the line, some c'tor of ours will not have an explicit this(...) call. It will either have an explicit super(...) call, or no call at all, which ends up leading to the compiler generating a call to super().
    Note that the ability to call super(...) does not mean that that c'tor was inherited.
    I know that ChocolateChip extends Cookie, but the Cookie constructor isn't enacted when the new ChocolateChip object is defined... or is it?Yes, it is. As I pointed out above, if we don't explicitly call this(...) or super(...), then a call to super() is inserted by the compiler.

  • Help with constructors using inheritance

    hi,
    i am having trouble with contructors in inheritance.
    i have a class Seahorse extends Move extends Animal
    in animal class , i have this constructor .
    public class Animal() {
    public Animal (char print, int maxage, int speed) {
    this.print = print;
    this.maxage = maxage;
    this.speed = speed;
    public class Move extends Animal {
    public Move(char print, int maxage, int speed)
    super(print, maxage, speed); //do i even need this here? if i dont i
    //get an error in Seahorse class saying super() not found
    public class Seahorse extends Move {
    public Seahorse(char print, int maxage, int speed)
    super('H',10,0);
    please help

    It's not a problem, it's how Java works. First, if you do not create a constructor in your code, the compiler will generate a default constructor that does not take any arguments. If you do create one or more constructors, the only way to construct an object instance of the class is to use one of the constructors.
    Second, when you extend a class, your are saying the subclass "is a" implementation of the super class. In your case, you are saying Move is an Animal, and Seahorse is a Move (and an Animal as well). This does not seem like a good logical design, but that's a different problem.
    Since you specified that an Animal can only be constructed by passing a char, int, and int, that means that a Move can only be constructed by calling the super class constructor and passing a char, int, and int. Since Move can only be constructed using a char, int and int, Seahorse can only be constructed by calling super(char, int, int);.
    It is possible for a subclass to have a constructor that does not take the same parameters as the super class, but the subclass must call the super class constructor with the correct arguments. For example, you could have.
    public Seahorse() {
       super('S',2,5);
    }The other problem is, Move does not sound like a class. It sounds like a method. Perhaps you might have MobileAnimal, but that would only make sense if there was a corresponding StationaryAnimal. Your classes should model your problem. It's hard to image a problem in which a Seahorse is a Move, and a Move is an Animal. It makes more sense for Animals to be able to move(), which allows a Seahorse to move differently compared to an Octopus.

  • Question about constructors and inheritance

    Hello:
    I have these classes:
    public class TIntP4
        protected int val=0;
        public TIntP4(){val=0;}
        public TIntP4(int var)throws Exception
            if(var<0){throw new Exception("TIntP4: value must be positive: "+var);}
            val=var;
        public TIntP4(String var)throws Exception
            this(Integer.parseInt(var));
        public String toString()
            return val+"";
    public class TVF extends TIntP4
    }Using those clases, if I try to compile this:
    TVF  inst=new TVF("12");I get a compiler error: TVF(String) constructor can not be found. I wonder why constructor is not inherited, or if there is a way to avoid this problem without having to add the constructor to the subclass:
    public class TVF extends TIntP4
         public TVF (String var)throws Exception
              super(var);
    }Thanks!!

    I guess that it would not help adding the default constructor:
    public class TVF extends TIntP4
         public TVF ()
               super();
         public TVF (String var)throws Exception
              super(var);
    }The point is that if I had in my super class 4 constructors, should I implement them all in the subclass although I just call the super class constructors?
    Thanks again!

  • Default constructor and inheritance

    Hi all.
    I have a class that represents a contact. A contact object is valid if both name and number have been specified. Otherwise I want to be notified via a dedicated exception.
    This is the code:
    public class Contact
        private String contact[] = new String[2];
        public Contact(String name, String number) throws InvalidContactException
            setName(name); // a method to set contact[0]
            setNumber(number); // a method to set contact[1]
            if (isValid()) // a method to check if both name and number have been specified.
                throw new InvalidContactException(); // this class inherits from Exception.
            // other class methods.
    }This is my questions:
    As the the constructor public Contact() wouldn't create a valid object, I have omitted it. Is it a good thing? I know that if some new class will extend Contact by inheritance, its default constructor will call the default constructor of super class (Contact), which does not provide one. This probably will cause some kind of error.
    Then I thought to provide a such constructor:
    public Contact() throws InvalidContactException()
    this("", ""); // It asks for a not valid contact.
    }I don't feel it's a clean solution, am I following an acceptable way?
    Thanks for your attention

    I'm not sure what your point is, especially thepart
    about "since the JMM is broken, the order cannotbe
    guaranteed." Can you be more specific? The JLS is
    quite specific on what happens and in what orderwhen
    an object is created, including when an exceptionis
    thrown.
    [url
    http://java.sun.com/docs/books/jls/third_edition/html/
    execution.html#12.5]JLS 12.5 Creation of New
    Class
    Instances
    What downside are you claiming to throwing an
    exception from a c'tor?IMHO The JLS does specify the steps but doesnot
    mention the order. Please correct me if it specifies
    the order as well.
    Read that section. The order is the order it states there.
    >
    If an exception is thrown in a constructor would an
    object be created or not?
    A a = new A();
    Depends what you mean by "object created." The memory is allocated. Which of the rest of the steps have been run (instance initializers, ancestor c'tors, this c'tor) depend on where the exception was thrown. Regardless, though, you won't get back a value in the variable a.
    now the constructor A() throwns and exception. My
    question is would a be null in that case or not?a will have whatever value it had before that method, if any. But it doesn't matter, because, since an exception has been thrown, the steps after that statement are not executed.
    Specially considering as I mentioned the order is not
    guaranteed in my previous post and JMM is broken.You have yet to provide support or clarification for this, or what it means in this context.
    Considering a might or might not be null ,There is no "might or might not." See above.
    what
    would be the benefit of such an exception.
    Following the broken DCL semantics and I am sure
    you must have gone through articleDCL is a completely different issue.

  • Why are Constructor not inherited?

    Hello,
    how come Java Constructors are not inherited by subclasses? Consider:
    ClassA
    ClassA(someParameters)
    ClassB extends ClassA
    How come do I need to declare a Constructor in ClassB that will accept "someParameters"? Why don't my ClassB simply inherites its parent Constructor?
    Thanks for any insights :-)
    PA.

    Hi,
    Straight from the Java Language Specs:
    2.12 Constructors
    A constructor is used in the creation of an object that is an instance of a class. The constructor declaration looks like a method declaration that has no result type. Constructors are invoked by class instance creation expressions, by the conversions and concatenations caused by the string concatenation operator +, and by explicit constructor invocations from other constructors; they are never invoked by method invocation expressions.
    Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.
    If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body is implicitly assumed by the compiler to begin with a superclass constructor invocation "super();", an invocation of the constructor of the direct superclass that takes no arguments.
    If a class declares no constructors then a default constructor, which takes no arguments, is automatically provided. If the class being declared is Object, then the default constructor has an empty body. Otherwise, the default constructor takes no arguments and simply invokes the superclass constructor with no arguments. If the class is declared public, then the default constructor is implicitly given the access modifier public. Otherwise, the default constructor has the default access implied by no access modifier.
    A class can be designed to prevent code outside the class declaration from creating instances of the class by declaring at least one constructor, in order to prevent the creation of an implicit constructor, and declaring all constructors to be private.
    This should answer your question and then some.
    Try reading the JLS yourself to get answers as to why ... then come back here and get help with how.
    http://java.sun.com/docs/books/vmspec/2nd-edition/html/VMSpecTOC.doc.html
    Regards,
    Manfred.

  • Private Constructors and Inheritance

    Hi,
    I have created a class according to the Singleton pattern, with a private constructor to prevent the public creation of class instances. Now I'd like to sub-class the Singleton, but I get errors saying the Singleton constructor is not visible. I guess this is caused by the privateness of the constructor, but I don't know if changing it to protected would ruin the Singleton pattern. Is there a good way to sub-class a Singleton?

    public class SingletonBase {
        private static SingletonBase instance;
        protected SingletonBase() throws InstantiationException {
            synchronized (SingletonBase.class) {
                if (instance != null)
                    throw new InstantiationException("single instance already exists");
                else
                    instance = this;
        public static SingletonBase getInstance() {
            return instance;
    }

  • Errors in making jar file

    Hi all,
    The following is the simple bean I try to make
    import java.awt.*;
    import java.io.Serializable;
    public class SimpleBean extends Canvas
    implements Serializable {
    private Color color = Color.green;
    //getter method
    public Color getColor() {
         return color;
    //setter method
    public void setColor(Color newColor) {
         color = newColor;
         repaint();
    //override paint method
    public void paint (Graphics g) {
         g.setColor(color);
         g.fillRect(20,5,20,30);
    //Constructor: sets inherited properties
    public SimpleBean() {
         setSize(60,40);
         setBackground(Color.red);
    It is compile without problem. Now I try to make a jar file. First, I made a manifest file as follow:
    Name:SimpleBean.class
    Java-Bean:True
    and I had a carriage return at end of the file. Next, I issue
    jar cfm SimpleBean.jar manifest.tmp SimpleBean.class
    at the command line, but I got:
    java.io.IOException: invalid header field
    at java.util.jar.Attributes.read(Attributes.java:353)
    at java.util.jar.Manifest.read(Manifest.java:159)
    at java.util.jar.Manifest.<init>(Manifest.java:59)
    at sun.tools.jar.Main.run(Main.java:124)
    at sun.tools.jar.Main.main(Main.java:778)
    What did I do wrong? Please help,
    Wei

    check this http://java.sun.com/docs/books/tutorial/jar/basics/manifest.html

  • A Bean must implement the java.io.Serializable interface? What makes the di

    Hi, I have took an example from sun notes on JavaBeans (you can find the example here http://java.sun.com/developer/onlineTraining/Beans/beans02/page2.html). The code is like this.....
    import java.awt.*;
    import java.io.Serializable;
    public class SimpleBean extends Canvas
                     implements Serializable {
      private Color color = Color.green;
      //getter method
      public Color getColor() {
         return color;
      //setter method
      public void setColor(Color newColor) {
         color = newColor;
         repaint();
      //override paint method
      public void paint (Graphics g) {
         g.setColor(color);
         g.fillRect(20,5,20,30);
      //Constructor: sets inherited properties
      public SimpleBean() {
         setSize(60,40);
         setBackground(Color.red);
    }I didn't find any difference in executing the program by implementing the Serializable interface and without implementing. On choosing serialize component in the File Menu, I serialized the component after changing its color (property), and saved as .ser file. And created the .Jar file including .ser file. when I load the jar file and place the bean in the beanbox, it is showing the bean that is updated. This can be done by implemeting Serializable interface and without implementing Serializable interface also. And I have a statement that has been given in the notes provided by SUN. That is ' Bean must implement the Serializable interface. Objects that support this interface can save and restore their state from disk '. I couldnot come up with the summation of this statement.
    Anyone who has an idea... please give an explanation.
    Thank you.

    Maybe you should show us your coding how you saved your beans state.
    Are you serious that you save the special object? Or do you save the values of the object into a file and load those values into a new object?

  • Java3D About KBCubicSplineSegment

    Why the constructor of KBCubicSplineSegment is non-public�HI cannot use it in my code. I tried to rewrite the constructor in inherited class but failed.
    The compiler notify me "implicit super constructor KBCubicSplineSegment() is not visible.Must explicitly invoke another constructor"
    Why? How can I use this class? Any particular special structure in this class here?
    Edited by: KelvinZhao on Apr 1, 2008 6:59 PM

    The source code here
    ===================================
    001:        /*
    002:         * $RCSfile: KBCubicSplineSegment.java,v $
    003:         *
    004:         * Copyright (c) 2007 Sun Microsystems, Inc. All rights reserved.
    005:         *
    006:         * Redistribution and use in source and binary forms, with or without
    007:         * modification, are permitted provided that the following conditions
    008:         * are met:
    009:         *
    010:         * - Redistribution of source code must retain the above copyright
    011:         *   notice, this list of conditions and the following disclaimer.
    012:         *
    013:         * - Redistribution in binary form must reproduce the above copyright
    014:         *   notice, this list of conditions and the following disclaimer in
    015:         *   the documentation and/or other materials provided with the
    016:         *   distribution.
    017:         *
    018:         * Neither the name of Sun Microsystems, Inc. or the names of
    019:         * contributors may be used to endorse or promote products derived
    020:         * from this software without specific prior written permission.
    021:         *
    022:         * This software is provided "AS IS," without a warranty of any
    023:         * kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
    024:         * WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
    025:         * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
    026:         * EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL
    027:         * NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF
    028:         * USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
    029:         * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR
    030:         * ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
    031:         * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
    032:         * REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
    033:         * INABILITY TO USE THIS SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
    034:         * POSSIBILITY OF SUCH DAMAGES.
    035:         *
    036:         * You acknowledge that this software is not designed, licensed or
    037:         * intended for use in the design, construction, operation or
    038:         * maintenance of any nuclear facility.
    039:         *
    040:         * $Revision: 1.4 $
    041:         * $Date: 2007/02/09 17:20:11 $
    042:         * $State: Exp $
    043:         */
    044:
    045:        package com.sun.j3d.utils.behaviors.interpolators;
    046:
    047:        import javax.media.j3d.*;
    048:        import java.util.*;
    049:        import javax.vecmath.*;
    050:
    051:        /**
    052:         * The KBCubicSplineSegment class creates the representation of a
    053:         * Kochanek-Bartel's (also known as the TCB or Tension-Continuity-Bias
    054:         * Spline.  This class takes 4 key frames as its input (using KBKeyFrame).
    055:         * If interpolating between the i<sup>th</sup> and (i+1)<sup>th</sup> key
    056:         * frame then the four key frames that need to be specified are the
    057:         * (i-1)<sup>th</sup>, i<sup>th</sup>, (i+1)<sup>th</sup>
    058:         * and (i+2)<sup>th</sup>  keyframes in order. The KBCubicSegmentClass
    059:         * then pre-computes the hermite interpolation basis coefficients if the
    060:         * (i+1)<sup>th</sup> frame has the linear flag set to zero. These are used to
    061:         * calculate the interpolated position, scale and quaternions when they
    062:         * requested by the user using the getInterpolated* methods. If the the
    063:         * (i+1)<sup>th</sup> frame's linear flag is set to 1 then the class uses
    064:         * linear interpolation to calculate the interpolated position, scale, heading
    065:         * pitch and bank it returns through the getInterpolated* methods.
    066:         *
    067:         * @since Java3D 1.2
    068:         */
    069:        public class KBCubicSplineSegment {
    070:
    071:            // Legendre polynomial information for Gaussian quadrature of speed
    072:            // for the domain [0,u], 0 <= u <= 1.
    073:
    074:            // Legendre roots mapped to (root+1)/2
    075:            static final double modRoot[] = { 0.046910077, 0.230765345, 0.5,
    076:                    0.769234655, 0.953089922 };
    077:
    078:            // original coefficients divided by 2
    079:            static final double modCoeff[] = { 0.118463442, 0.239314335,
    080:                    0.284444444, 0.239314335, 0.118463442 };
    081:
    082:            // Key Frames
    083:            KBKeyFrame[] keyFrame = new KBKeyFrame[4];
    084:
    085:            // H.C
    086:            Point3f c0, c1, c2, c3; // coefficients for position
    087:            Point3f e0, e1, e2, e3; // coefficients for scale
    088:            float h0, h1, h2, h3; // coefficients for heading 
    089:            float p0, p1, p2, p3; // coefficients for pitch
    090:            float b0, b1, b2, b3; // coefficients for bank
    091:
    092:            // variables for destination derivative
    093:            float one_minus_t_in;
    094:            float one_minus_c_in;
    095:            float one_minus_b_in;
    096:            float one_plus_c_in;
    097:            float one_plus_b_in;
    098:            float ddb;
    099:            float dda;
    100:
    101:            // variables for source derivative
    102:            float one_minus_t_out;
    103:            float one_minus_c_out;
    104:            float one_minus_b_out;
    105:            float one_plus_c_out;
    106:            float one_plus_b_out;
    107:            float dsb;
    108:            float dsa;
    109:
    110:            // Length of the spline segment
    111:            float length;
    112:
    113:            // interpolation type
    114:            int linear;
    115:
    116:            // Default constructor
    117:            KBCubicSplineSegment() {
    118:
    119:                length = 0;
    120:
    121:            }
    122:
    123:            /**
    124:             * Creates a cubic spline segment between two key frames using the
    125:             * key frames provided. If creating a spline between the ith frame and
    126:             * the (i+1)<sup>th</sup> frame then send down the (i - 1)<sup>th</sup>,
    127:             * i<sup>th</sup> , (i+1)<sup>th</sup> and the (i+2)<sup>th</sup> key
    128:             * frames. 
    129:             *
    130:             * @param kf0 (i - 1)<sup>th</sup> Key Frame
    131:             * @param kf1 i<sup>th</sup> Key Frame
    132:             * @param kf2 (i + 1)<sup>th</sup> Key Frame
    133:             * @param kf3 (i + 2)<sup>th</sup> Key Frame
    134:             */
    135:
    136:            KBCubicSplineSegment(KBKeyFrame kf0, KBKeyFrame kf1,
    137:                    KBKeyFrame kf2, KBKeyFrame kf3) {
    138:
    139:                // Copy KeyFrame information
    140:                keyFrame[0] = new KBKeyFrame(kf0);
    141:                keyFrame[1] = new KBKeyFrame(kf1);
    142:                keyFrame[2] = new KBKeyFrame(kf2);
    143:                keyFrame[3] = new KBKeyFrame(kf3);
    144:
    145:                // if linear interpolation is requested then just set linear flag
    146:                // if spline interpolation is needed then compute spline coefficients
    147:                if (kf2.linear == 1) {
    148:                    this .linear = 1;
    149:                } else {
    150:                    this .linear = 0;
    151:                    computeCommonCoefficients(kf0, kf1, kf2, kf3);
    152:                    computeHermiteCoefficients(kf0, kf1, kf2, kf3);
    153:                }
    154:
    155:                length = computeLength(1.0f);
    156:                // System.out.println ("Segment length = " + length);
    157:
    158:            }
    159:
    160:            // compute the common coefficients
    161:            private void computeCommonCoefficients(KBKeyFrame kf0,
    162:                    KBKeyFrame kf1, KBKeyFrame kf2, KBKeyFrame kf3) {
    163:
    164:                // variables for destination derivative
    165:                float one_minus_t_in = 1.0f - kf1.tension;
    166:                float one_minus_c_in = 1.0f - kf1.continuity;
    167:                float one_minus_b_in = 1.0f - kf1.bias;
    168:                float one_plus_c_in = 1.0f + kf1.continuity;
    169:                float one_plus_b_in = 1.0f + kf1.bias;
    170:
    171:                // coefficients for the incoming Tangent
    172:                ddb = one_minus_t_in * one_minus_c_in * one_minus_b_in;
    173:                dda = one_minus_t_in * one_plus_c_in * one_plus_b_in;
    174:
    175:                // variables for source derivative
    176:                float one_minus_t_out = 1.0f - kf2.tension;
    177:                float one_minus_c_out = 1.0f - kf2.continuity;
    178:                float one_minus_b_out = 1.0f - kf2.bias;
    179:                float one_plus_c_out = 1.0f + kf2.continuity;
    180:                float one_plus_b_out = 1.0f + kf2.bias;
    181:
    182:                // coefficients for the outgoing Tangent
    183:                dsb = one_minus_t_in * one_plus_c_in * one_minus_b_in;
    184:                dsa = one_minus_t_in * one_minus_c_in * one_plus_b_in;
    185:            }
    186:
    187:            // compute the hermite interpolation basis coefficients
    188:            private void computeHermiteCoefficients(KBKeyFrame kf0,
    189:                    KBKeyFrame kf1, KBKeyFrame kf2, KBKeyFrame kf3) {
    190:
    191:                Point3f deltaP = new Point3f();
    192:                Point3f deltaS = new Point3f();
    193:                float deltaH;
    194:                float deltaT;
    195:                float deltaB;
    196:
    197:                // Find the difference in position and scale
    198:                deltaP.x = kf2.position.x - kf1.position.x;
    199:                deltaP.y = kf2.position.y - kf1.position.y;
    200:                deltaP.z = kf2.position.z - kf1.position.z;
    201:
    202:                deltaS.x = kf2.scale.x - kf1.scale.x;
    203:                deltaS.y = kf2.scale.y - kf1.scale.y;
    204:                deltaS.z = kf2.scale.z - kf1.scale.z;
    205:
    206:                // Find the difference in heading, pitch, and bank
    207:                deltaH = kf2.heading - kf1.heading;
    208:                deltaT = kf2.pitch - kf1.pitch;
    209:                deltaB = kf2.bank - kf1.bank;
    210:
    211:                // Incoming Tangent
    212:                Point3f dd_pos = new Point3f();
    213:                Point3f dd_scale = new Point3f();
    214:                float dd_heading, dd_pitch, dd_bank;
    215:
    216:                // If this is the first keyframe of the animation
    217:                if (kf0.knot == kf1.knot) {
    218:
    219:                    float ddab = 0.5f * (dda + ddb);
    220:
    221:                    // Position
    222:                    dd_pos.x = ddab * deltaP.x;
    223:                    dd_pos.y = ddab * deltaP.y;
    224:                    dd_pos.z = ddab * deltaP.z;
    225:
    226:                    // Scale
    227:                    dd_scale.x = ddab * deltaS.x;
    228:                    dd_scale.y = ddab * deltaS.y;
    229:                    dd_scale.z = ddab * deltaS.z;
    230:
    231:                    // Heading, Pitch and Bank
    232:                    dd_heading = ddab * deltaH;
    233:                    dd_pitch = ddab * deltaT;
    234:                    dd_bank = ddab * deltaB;
    235:
    236:                } else {
    237:
    238:                    float adj0 = (kf1.knot - kf0.knot) / (kf2.knot - kf0.knot);
    239:
    240:                    // Position
    241:                    dd_pos.x = adj0
    242:                            * ((ddb * deltaP.x) + (dda * (kf1.position.x - kf0.position.x)));
    243:                    dd_pos.y = adj0
    244:                            * ((ddb * deltaP.y) + (dda * (kf1.position.y - kf0.position.y)));
    245:                    dd_pos.z = adj0
    246:                            * ((ddb * deltaP.z) + (dda * (kf1.position.z - kf0.position.z)));
    247:
    248:                    // Scale
    249:                    dd_scale.x = adj0
    250:                            * ((ddb * deltaS.x) + (dda * (kf1.scale.x - kf0.scale.x)));
    251:                    dd_scale.y = adj0
    252:                            * ((ddb * deltaS.y) + (dda * (kf1.scale.y - kf0.scale.y)));
    253:                    dd_scale.z = adj0
    254:                            * ((ddb * deltaS.z) + (dda * (kf1.scale.z - kf0.scale.z)));
    255:
    256:                    // Heading, Pitch and Bank
    257:                    dd_heading = adj0
    258:                            * ((ddb * deltaH) + (dda * (kf1.heading - kf0.heading)));
    259:                    dd_pitch = adj0
    260:                            * ((ddb * deltaT) + (dda * (kf1.pitch - kf0.pitch)));
    261:                    dd_bank = adj0
    262:                            * ((ddb * deltaB) + (dda * (kf1.bank - kf0.bank)));
    263:                }
    264:
    265:                // Outgoing Tangent
    266:                Point3f ds_pos = new Point3f();
    267:                Point3f ds_scale = new Point3f();
    268:                float ds_heading, ds_pitch, ds_bank;
    269:
    270:                // If this is the last keyframe of the animation
    271:                if (kf2.knot == kf3.knot) {
    272:
    273:                    float dsab = 0.5f * (dsa + dsb);
    274:
    275:                    // Position
    276:                    ds_pos.x = dsab * deltaP.x;
    277:                    ds_pos.y = dsab * deltaP.y;
    278:                    ds_pos.z = dsab * deltaP.z;
    279:
    280:                    // Scale
    281:                    ds_scale.x = dsab * deltaS.x;
    282:                    ds_scale.y = dsab * deltaS.y;
    283:                    ds_scale.z = dsab * deltaS.z;
    284:
    285:                    // Heading, Pitch and Bank
    286:                    ds_heading = dsab * deltaH;
    287:                    ds_pitch = dsab * deltaT;
    288:                    ds_bank = dsab * deltaB;
    289:
    290:                } else {
    291:
    292:                    float adj1 = (kf2.knot - kf1.knot) / (kf3.knot - kf1.knot);
    293:
    294:                    // Position
    295:                    ds_pos.x = adj1
    296:                            * ((dsb * (kf3.position.x - kf2.position.x)) + (dsa * deltaP.x));
    297:                    ds_pos.y = adj1
    298:                            * ((dsb * (kf3.position.y - kf2.position.y)) + (dsa * deltaP.y));
    299:                    ds_pos.z = adj1
    300:                            * ((dsb * (kf3.position.z - kf2.position.z)) + (dsa * deltaP.z));
    301:
    302:                    // Scale
    303:                    ds_scale.x = adj1
    304:                            * ((dsb * (kf3.scale.x - kf2.scale.x)) + (dsa * deltaS.x));
    305:                    ds_scale.y = adj1
    306:                            * ((dsb * (kf3.scale.y - kf2.scale.y)) + (dsa * deltaS.y));
    307:                    ds_scale.z = adj1
    308:                            * ((dsb * (kf3.scale.z - kf2.scale.z)) + (dsa * deltaS.z));
    309:
    310:                    // Heading, Pitch and Bank
    311:                    ds_heading = adj1
    312:                            * ((dsb * (kf3.heading - kf2.heading)) + (dsa * deltaH));
    313:                    ds_pitch = adj1
    314:                            * ((dsb * (kf3.pitch - kf2.pitch)) + (dsa * deltaT));
    315:                    ds_bank = adj1
    316:                            * ((dsb * (kf3.bank - kf2.bank)) + (dsa * deltaB));
    317:                }
    318:
    319:                // Calculate the coefficients of the polynomial for position
    320:                c0 = new Point3f();
    321:                c0.x = kf1.position.x;
    322:                c0.y = kf1.position.y;
    323:                c0.z = kf1.position.z;
    324:
    325:                c1 = new Point3f();
    326:                c1.x = dd_pos.x;
    327:                c1.y = dd_pos.y;
    328:                c1.z = dd_pos.z;
    329:
    330:                c2 = new Point3f();
    331:                c2.x = 3 * deltaP.x - 2 * dd_pos.x - ds_pos.x;
    332:                c2.y = 3 * deltaP.y - 2 * dd_pos.y - ds_pos.y;
    333:                c2.z = 3 * deltaP.z - 2 * dd_pos.z - ds_pos.z;
    334:
    335:                c3 = new Point3f();
    336:                c3.x = -2 * deltaP.x + dd_pos.x + ds_pos.x;
    337:                c3.y = -2 * deltaP.y + dd_pos.y + ds_pos.y;
    338:                c3.z = -2 * deltaP.z + dd_pos.z + ds_pos.z;
    339:
    340:                // Calculate the coefficients of the polynomial for scale
    341:                e0 = new Point3f();
    342:                e0.x = kf1.scale.x;
    343:                e0.y = kf1.scale.y;
    344:                e0.z = kf1.scale.z;
    345:
    346:                e1 = new Point3f();
    347:                e1.x = dd_scale.x;
    348:                e1.y = dd_scale.y;
    349:                e1.z = dd_scale.z;
    350:
    351:                e2 = new Point3f();
    352:                e2.x = 3 * deltaS.x - 2 * dd_scale.x - ds_scale.x;
    353:                e2.y = 3 * deltaS.y - 2 * dd_scale.y - ds_scale.y;
    354:                e2.z = 3 * deltaS.z - 2 * dd_scale.z - ds_scale.z;
    355:
    356:                e3 = new Point3f();
    357:                e3.x = -2 * deltaS.x + dd_scale.x + ds_scale.x;
    358:                e3.y = -2 * deltaS.y + dd_scale.y + ds_scale.y;
    359:                e3.z = -2 * deltaS.z + dd_scale.z + ds_scale.z;
    360:
    361:                // Calculate the coefficients of the polynomial for heading, pitch
    362:                // and bank
    363:                h0 = kf1.heading;
    364:                p0 = kf1.pitch;
    365:                b0 = kf1.bank;
    366:
    367:                h1 = dd_heading;
    368:                p1 = dd_pitch;
    369:                b1 = dd_bank;
    370:
    371:                h2 = 3 * deltaH - 2 * dd_heading - ds_heading;
    372:                p2 = 3 * deltaT - 2 * dd_pitch - ds_pitch;
    373:                b2 = 3 * deltaB - 2 * dd_bank - ds_bank;
    374:
    375:                h3 = -2 * deltaH + dd_heading + ds_heading;
    376:                p3 = -2 * deltaT + dd_pitch + ds_pitch;
    377:                b3 = -2 * deltaB + dd_bank + ds_bank;
    378:            }
    379:
    380:            /**
    381:             * Computes the length of the curve at a given point between
    382:             * key frames.
    383:             * @param u specifies the point between keyframes where 0 <= u <= 1.
    384:             */
    385:
    386:            public float computeLength(float u) {
    387:
    388:                float result = 0f;
    389:
    390:                // if linear interpolation
    391:                if (linear == 1) {
    392:                    result = u
    393:                            * keyFrame[2].position
    394:                                    .distance(keyFrame[1].position);
    395:                } else {
    396:                    // Need to transform domain [0,u] to [-1,1].  If 0 <= x <= u
    397:                    // and -1 <= t <= 1, then x = u*(t+1)/2.
    398:                    int degree = 5;
    399:                    for (int i = 0; i < degree; i++)
    400:                        result += (float) modCoeff[i]
    401:                                * computeSpeed(u * (float) modRoot);
    402: result *= u;
    403: }
    404:
    405: return result;
    406: }
    407:
    408: // Velocity along curve
    409: private float computeSpeed(float u) {
    410: Point3f v = new Point3f();
    411:
    412: v.x = c1.x + u * (2 * c2.x + 3 * u * c3.x);
    413: v.y = c1.y + u * (2 * c2.y + 3 * u * c3.y);
    414: v.z = c1.z + u * (2 * c2.z + 3 * u * c3.z);
    415:
    416: return (float) (Math.sqrt(v.x * v.x + v.y * v.y + v.z * v.z));
    417: }
    418:
    419: /**
    420: * Computes the interpolated scale along the curve at a given point
    421: * between key frames and returns a Point3f with the interpolated
    422: * x, y, and z scale components. This routine uses linear
    423: * interpolation if the (i+1)<sup>th</sup> key frame's linear
    424: * value is equal to 1.
    425: *
    426: * @param u specifies the point between keyframes where 0 <= u <= 1.
    427: * @param newScale returns the interpolated x,y,z scale value in a Point3f
    428: */
    429:
    430: public void getInterpolatedScale(float u, Point3f newScale) {
    431:
    432: // if linear interpolation
    433: if (this .linear == 1) {
    434:
    435: newScale.x = keyFrame[1].scale.x
    436: + ((keyFrame[2].scale.x - keyFrame[1].scale.x) * u);
    437: newScale.y = keyFrame[1].scale.y
    438: + ((keyFrame[2].scale.y - keyFrame[1].scale.y) * u);
    439: newScale.z = keyFrame[1].scale.z
    440: + ((keyFrame[2].scale.z - keyFrame[1].scale.z) * u);
    441:
    442: } else {
    443:
    444: newScale.x = e0.x + u * (e1.x + u * (e2.x + u * e3.x));
    445: newScale.y = e0.y + u * (e1.y + u * (e2.y + u * e3.y));
    446: newScale.z = e0.z + u * (e1.z + u * (e2.z + u * e3.z));
    447:
    448: }
    449: }
    450:
    451: /**
    452: * Computes the interpolated position along the curve at a given point
    453: * between key frames and returns a Point3f with the interpolated
    454: * x, y, and z scale components. This routine uses linear
    455: * interpolation if the (i+1)<sup>th</sup> key frame's linear
    456: * value is equal to 1.
    457: *
    458: * @param u specifies the point between keyframes where 0 <= u <= 1.
    459: * @param newPos returns the interpolated x,y,z position in a Point3f
    460: */
    461:
    462: public void getInterpolatedPosition(float u, Point3f newPos) {
    463:
    464: // if linear interpolation
    465: if (this .linear == 1) {
    466: newPos.x = keyFrame[1].position.x
    467: + ((keyFrame[2].position.x - keyFrame[1].position.x) * u);
    468: newPos.y = keyFrame[1].position.y
    469: + ((keyFrame[2].position.y - keyFrame[1].position.y) * u);
    470: newPos.z = keyFrame[1].position.z
    471: + ((keyFrame[2].position.z - keyFrame[1].position.z) * u);
    472: } else {
    473:
    474: newPos.x = c0.x + u * (c1.x + u * (c2.x + u * c3.x));
    475: newPos.y = c0.y + u * (c1.y + u * (c2.y + u * c3.y));
    476: newPos.z = c0.z + u * (c1.z + u * (c2.z + u * c3.z));
    477:
    478: }
    479: }
    480:
    481: /**
    482: * Computes the interpolated position along the curve at a given point
    483: * between key frames and returns a Vector3f with the interpolated
    484: * x, y, and z scale components. This routine uses linear
    485: * interpolation if the (i+1)<sup>th</sup> key frame's linear
    486: * value is equal to 1.
    487: *
    488: * @param u specifies the point between keyframes where 0 <= u <= 1.
    489: * @param newPos returns the interpolated x,y,z position in a Vector3f.
    490: */
    491:
    492: public void getInterpolatedPositionVector(float u, Vector3f newPos) {
    493: // if linear interpolation
    494: if (this .linear == 1) {
    495: newPos.x = keyFrame[1].position.x
    496: + ((keyFrame[2].position.x - keyFrame[1].position.x) * u);
    497: newPos.y = keyFrame[1].position.y
    498: + ((keyFrame[2].position.y - keyFrame[1].position.y) * u);
    499: newPos.z = keyFrame[1].position.z
    500: + ((keyFrame[2].position.z - keyFrame[1].position.z) * u);
    501: } else {
    502:
    503: newPos.x = c0.x + u * (c1.x + u * (c2.x + u * c3.x));
    504: newPos.y = c0.y + u * (c1.y + u * (c2.y + u * c3.y));
    505: newPos.z = c0.z + u * (c1.z + u * (c2.z + u * c3.z));
    506:
    507: }
    508: }
    509:
    510: /**
    511: * Computes the interpolated heading along the curve at a given point
    512: * between key frames and returns the interpolated value as a float
    513: * This routine uses linear interpolation if the (i+1)<sup>th</sup>
    514: * key frame's linear value is equal to 1.
    515: *
    516: * @param u specifies the point between keyframes where 0 <= u <= 1.
    517: * @return returns the interpolated heading value
    518: */
    519:
    520: public float getInterpolatedHeading(float u) {
    521:
    522: float newHeading;
    523:
    524: // if linear interpolation
    525: if (this .linear == 1) {
    526:
    527: newHeading = keyFrame[1].heading
    528: + ((keyFrame[2].heading - keyFrame[1].heading) * u);
    529: } else {
    530:
    531: newHeading = h0 + u * (h1 + u * (h2 + u * h3));
    532:
    533: }
    534:
    535: return newHeading;
    536: }
    537:
    538: /**
    539: * Computes the interpolated pitch along the curve at a given point
    540: * between key frames and returns the interpolated value as a float
    541: * This routine uses linear interpolation if the (i+1)<sup>th</sup>
    542: * key frame's linear value is equal to 1.
    543: *
    544: * @param u specifies the point between keyframes where 0 <= u <= 1.
    545: * @return returns the interpolated pitch value
    546: */
    547:
    548: public float getInterpolatedPitch(float u) {
    549:
    550: float newPitch;
    551:
    552: // if linear interpolation
    553: if (this .linear == 1) {
    554:
    555: newPitch = keyFrame[1].pitch
    556: + ((keyFrame[2].pitch - keyFrame[1].pitch) * u);
    557: } else {
    558:
    559: newPitch = p0 + u * (p1 + u * (p2 + u * p3));
    560:
    561: }
    562:
    563: return newPitch;
    564: }
    565:
    566: /**
    567: * Computes the interpolated bank along the curve at a given point
    568: * between key frames and returns the interpolated value as a float
    569: * This routine uses linear interpolation if the (i+1)<sup>th</sup>
    570: * key frame's linear value is equal to 1.
    571: *
    572: * @param u specifies the point between keyframes where 0 <= u <= 1.
    573: * @return returns the interpolated bank value
    574: */
    575:
    576: public float getInterpolatedBank(float u) {
    577:
    578: float newBank;
    579:
    580: // if linear interpolation
    581: if (this .linear == 1) {
    582:
    583: newBank = keyFrame[1].bank
    584: + ((keyFrame[2].bank - keyFrame[1].bank) * u);
    585: } else {
    586:
    587: newBank = b0 + u * (b1 + u * (b2 + u * b3));
    588:
    589: }
    590:
    591: return newBank;
    592: }
    593:
    594: /**
    595: * Computes the ratio of the length of the spline from the i<sup>th</sup>
    596: * key frame to the position specified by u to the length of the entire
    597: * spline segment from the i<sup>th</sup> key frame to the (i+1)
    598: * <sup>th</sup> key frame. When the (i+1)<sup>th</sup> key frame's linear
    599: * value is equal to 1, this is meaninful otherwise it should return u.
    600: *
    601: * @param u specifies the point between keyframes where 0 <= u <= 1.
    602: * @return the interpolated ratio
    603: */
    604:
    605: public float getInterpolatedValue(float u) {
    606: return (computeLength(u) / this.length);
    607: }
    608: }Edited by: KelvinZhao on Apr 1, 2008 7:10 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Having a problem with inheritance and a constructor

    i have two classes, i'm just going to give the constructors anyway. I'm having trouble getting the CDImage constructor to inherit something from songs, I believe the instructions are missing something or the cs lab guy misinterpreted them.
    package songs;
    import java.text.*;
    public class Song implements Comparable {
        private int songLength;
        private String artistName;
        private String songName;
        public Song(int songLength, String artistNames, String songName) {
            this.songLength = songLength;
            this.artistName = artistNames;
            this.songName = songName;
        }These are the instructions that i beleive may be incorrect:
    Design a CDImage class to represent a music CD. The constructor takes three parameters: the title of the CD, the recording label, and the number of tracks on the CD. (Each track contains one song.) The CDImage class uses the Song class developed above and should contain methods to accomplish the following:package songs;
    import java.text.*;
    public class CDImage extends Song {
        private String title;
        private String label;
        private int numberTracks;
        private Song[] songs;
        public CDImage(String title, String label, int tracks){
        this.title = title;// this is the album name
        this.label = label;
        numberTracks = tracks;
        songs = new Song [numberTracks];
        }i know i need to use the super modifier under the constructor but how? because nothing in the constructor of the CDImage class refers directly to the constructor in the Song class
    thanks in advance.
    Message was edited by:
    kevin123

    you know whats funny, this project has to do with arrays of objects and not inheritance. We learned inheritance last week but the lab we are doing which is this, is for arrays of objects. sorry for the confusion lol. so you can completely ignore this, it actually has it in big bold letters at the top of the web page for the lab.

  • Inheritance Constructor error

    Hi guys, having a spot of bother with a constructor of a sub-class.
    What i am doing is making a super class... Person and a subclass... Administrator
    When i am coding my constructor for the administrator every inherited field constructs but my local one does not
    The error i get is on the constructor parameter, Cannot find symbol : constructor Person. class: Person
    I think it may be something to do with java not knowing what constructor to use
    Heres my code
    Personpublic abstract class Person{
        // TO DO
        // READ THE COMMENTS AND COMPLETE
        //Attributes
       public String name;
       public String address;
       public String sex;
       public int age;
           public Person(String name, String address, String sex, int age) {
            this.name = name;
            this.address = address;
            this.sex = sex;
            this.age = age;
        }Administrator
    public class Administrator extends Person {
        // Attributes
        private String type;
        // TO DO
        // READ THE COMMENTS AND COMPLETE
         * Constructor
         * @param name name of the administrator
         * @param address address of the administrator
         * @param gender sex of the administrator
         * @param age age of the administrator
         * @param type member type of the administrator
        public Administrator(String name, String address, String gender,
                int age, String type) {
            this.name=name;
            this.address=address;
            this.sex= gender;
            this.age=age;
            this.type=type;
        }

    If you don't explicity invoke a super constructor, the compiler inserts a call to the no-arg c'tor: super(); If your parent class does not have such a c'tor, that's an error. You'll need to add a call to
    super(name, age, gender);
    // or whatever parameters the parent's c'tor actually takesas the first line of your child class c'tor.

  • Constructor Inheritance Question

    Here's a quote from the Java Tutorials at http://java.sun.com/docs/books/tutorial/java/javaOO/objectcreation.html :
    "All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program."
    In order to fully understand this concept, I created two classes: a ClassParent and a ClassChild.
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
    public class ClassChild extends ClassParent
        public static void main(String[] args) {
            ClassChild child = new ClassChild();
    }Both classes compiled successfully, which raised the following question:
    I understand that the ClassParent default constructor calls the Object's no-argument constructor.
    Does the ClassChild also call the Object's constructor once it realizes that the ClassParent does not have a no-argument constructor?
    And a somewhat non-related question:
    Seeing how ClassParent calls Object's no-argument constructor if it does not have one of its own, does it also extend the Object class?
    Edit: After running the following code, I realized that the answer to my last question is yes:
    public class ClassParent
        public static void main(String[] args) {
           ClassParent tester = new ClassParent();
           boolean test = tester instanceof Object;
           System.out.println(test);
    }Edited by: youmefriend722 on May 26, 2008 1:54 PM

    youmefriend722 wrote:
    I think I'm getting a basic grasp now but want to make sure that I'm not misunderstanding anything.
    Constructor inheritance:
    If a no-argument constructor is invoked but one isn't declared in that class, the superclass's no-argument constructor will be invoked. Well, sort of. If you invoke a constructor that doesn't exist, you get an error. Keep in mind that the invocation and the constructor may both be automatically supplied by the compiler, and that the compiler won't automatically create a no-arg constructor for a class if you define any constructors for that class.
    So if you don't define any constructors in a class, then a no-arg one is created automatically (at compile time) and (at runtime) when you instantiate that class, that no-arg constructor will try to invoke the superclass's no-arg constructor.
    But suppose you do define a constructor, one that takes an argument. Then if you try to invoke a no-arg constructor on that class, you'll get an error, and the superclass's no-arg constructor won't be invoked (because the error happens first).
    If the superclass does not have a constructor, then the superclass's superclass's constructor will be invoked.No. That never happens. Every class has a constructor (although it might have permissions which make it inaccessible, which is a whole other issue we'll worry about later).
    If the superclass does have a constructor but doesn't have a no-argument constructor, then there will be a compile-time error.Only if you try to invoke the no-arg constructor, which might happen implicitly. For example, if you write a superclass with a 2-arg constructor, and you write a subclass with a 1-arg constructor, and the 1-arg subclass's constructor invokes the superclass's 2-arg constructor, then there's no problem, even though in this example, the superclass doesn't have a no-arg constructor.
    Constructors in general:
    In every constructor, the superclass's no-argument constructor will be invoked if the none of the superclass's constructors are explicitly invoked.Yeah, I think that's right.

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

  • Inheritance Issue - constructor

    Okay, I hope you guys can help me out of this. I currently have an interface designed, with a class inheriting its information. Here is the sample code for reference:
    ArrayStack
    public class ArrayStack
        implements AnotherInterface
        public ArrayStack(int stacksize)
            stack = new String[stacksize];
        public boolean isFull()
            return top == stack.length;
    }Now the problem arises when I want to create a new class which inherits the ArrayStack. Here is a sample code of what I have wrote up:
    public class checkSize extends ArrayStack
        public checkSize()
    }I'm just trying to get my head around inheritance, but this code keeps giving me the error "cannot find symbol - constructor". Can anyone point me to the right direction or tell me what I can do? Any help would be greatly appreciated!

    Connex007 wrote:
    Melanie_Green wrote:
    So as suggested you can either call another constructor or you can create a default constructor in your superclass,Now that's where I'm getting confused on - what other constructor can I call?There is only one other constructor to call in the super class.
    Remember that the first line of every constructor is either an explicit or implicit call to another constructor. If you do not explicitly call another constructor then super() is inserted during compile time, and the default constructor that has no parameters of the superclass is called.
    Furthermore any class that does not explicitly extend another class, extends Object. So as I stated previously if the first line of the any constructor in this class is not a call to another constructor, then the compiler will insert super() which will invoke the default constructor of Object.
    Now in your scenario you are using inheritance, you have a subclass extending a superclass. Note that you have not defined a default constructor in the super class, which for example is defined in Object. So inside your subclass, if you do not call another constructor on the first line, then again the compiler will insert a call to super(). The call to super() from the subclass is dependent on the superclass having defined a default no parameter constructor. However in your case the superclass does not have such a constructor defined. Therefore you are still required to instantiate every class in the inheritance tree, either explicitly or implicitly.
    If you are still weary at this point, think of it this way. If A extends B extends C. When an object of type A is instantiated, a constructor of A then B then C is called so that C is instantiated first, then B, then A. This is reflective of instantiated in a top down method so that each subclass is instantiated correctly. Since A extends B, and B can potentially be instantiated in one or more ways, you still need to define how both A and B are instantiated.
    So relating this back to your problem, what are all the possible ways in which your superclass can be instantiated? We can eliminate the default constructor and assume that we must specify on the first line of the constructor contained in the subclass that a call to a constructor in the subclass or superclass occurs. If we invoke a constructor in the same class, in the subclass, then either this constructor calls a constructor in the super class, or it calls a constructor that in turn will tinkle its way up to calling a constructor in the superclass.
    Mel

Maybe you are looking for

  • Problem with Pro*C/C++ complie in linux

    I install Oracle8.1.7 in my Mandrake 7.2 ( like redhat7.1) , and it works well except with proc not works well. when I complie the precomp demo program, it gives much errors. I note the proc config file length was zero. The following is errors I get

  • MSI GTX560 M2DIGD5

    Hello, Yesterday I tried installing my new MSI GTX560 graphic card. It's properly connected to my mainbord, and screwed in place. Today, I found out my computer isn't using the graphic card, but the onboard graphics. The graphic card could not be fou

  • What is the best way to get Previous Year calculations?

    Hi. I am having trouble building Previous Year calculations in OBIEE 11g. The "Ago" function is not working for me. At my company previous year is defined as Date - 364 (not Year - 1). Here is an example of the Answers report I am trying to build: Di

  • How to add delimiters to the csv output sent to outlook?

    Hi, our application server 10.1.2 host oracle reports, we need to send the csv output of the oracle reports to the emails of clients, we can send in format = 'ascii' but delimiter such as double quote("), comma(,) can not be added.

  • Selected task "{0}" in task scheduler

    I have read all the data online. I have gone through each of the library/microsoft/windows and removed from the extra items from the C:\Windows\System32\Tasks\Microsoft\Windows folders that didn't match up. I continue to get errors. Can you help? I h