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;
}

Similar Messages

  • Private attributes and Inheritance.

    I have a question regarding 'private attributes and inheritance'.
    If I have a class that will be extended by other classes,(basically
    this will act as a BASE class ),then why do I need to define
    any attribute private to this base class.?
    If I define an attribute as private in the base class,then the subclass cannot access
    this attribute.Right?
    1) Why define a private attribute in the base class ?
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?

    If I define an attribute as private in the base
    class,then the subclass cannot access
    this attribute.Right?Right. A simple example would tell you this.
    >
    1) Why define a private attribute in the base class?Because information hiding and encapsulation are always good things, even between super and sub classes.
    >
    2) When can a situation arise whereby the base class attribute is defined
    as 'private' and the base class is also extensible?This question makes no sense whatsoever. A base class is extensible, unless it is marked as final, whether or not it's got private data members.
    Objects usually have private state and public interfaces. The idea is that clients of a class, even subclasses, should only access the private state thorugh the public interface. So if you've designed your classes properly you shouldn't need to access that private state.
    If you do, you can always provide get/set methods.
    OR declare the data members as protected. That way they're package visible and available to subclasses.
    But private members do not make a class inextensible.
    %

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

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

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

  • Class with private constructor can be extended or not

    Hi All,
    I have a doubt.
    if a class has private constructor and there are some methods in this class.Can this class be extended and if yes how can we call its method in subclass?
    Thanks
    Sumit

    Karanjit wrote:
    If a class contains only private constructors, then it cannot be extended.Err... not the whole story!
    public class Sabre20090603a
        static class Fred extends Sabre20090603a
            Fred()
                super();
        private Sabre20090603a()
    }

  • Final class and private constructor

    Whats the difference in a final class and a class with private constructot?
    If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)

    You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
    KajThat depends on the signature of the private constructor.
    If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
    If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
    class Private1 {
         private int q;
         private Private1() {
         public Private1(int i) {
              q = i;
         public void print() {
              System.out.println(q);
    public class Public1 extends Private1 {
         public Public1() {
              super(1);
         public static void main(String[] args) {
              new Public1().print();
    }for example compiles and runs perfectly.
    But remove the call "super(1);" from the constructor and it will fail to compile.

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

  • Difference between public void, private void and public string

    Hi everyone,
    My 1st question is how do you know when to use public void, private void and public string? I am mightily cofuse with this.
    2ndly, Can anybody explain to me on following code snippet:
    Traceback B0;//the starting point  of Traceback
    // Traceback objects
    abstract class Traceback {
      int i, j;                     // absolute coordinates
    // Traceback2 objects for simple gap costs
    class Traceback2 extends Traceback {
      public Traceback2(int i, int j)
      { this.i = i; this.j = j; }
    }And using the code above is the following allowed:
    B[0] = new Traceback2(i-1, 0);
    Any replies much appreciated. Thank you.

    1)
    public and private are access modifiers,
    void and String return type declarations.
    2)
    It's called "inheritance", and "bad design" as well.
    You should read the tutorials, you know?

  • First Try with JE BDB - Indexes and Inheritance troubles... (FIXED)

    Hi Mark,
    Mark wrote:
    Hi, I'm a newbie here trying some stuff on JE BDB. And now I'm having
    I am happy to help you with this, but I'll have to ask you to re-post this question to the BDB JE forum, which is...
    Sorry for the mistake. I know now that here is the place to post my doubts.
    I'm really interested in JE BDB product. I think it is fantastic!
    Regarding my first post about "Indexes and Inheritance" on JE BDB, I found out the fix for that and actually, it wasn't about "Indexes and Inheritance" but "*Inheritance and Sequence*" because I have my "@Persistent public abstract class AbstractEntity" with a "@PrimaryKey(sequence = "ID_SEQ") private Long id" property.
    This class is extended by all my business classes (@Entity Employee and @Entity Department) so that my business classes have their PrimaryKey autoincremented by the sequence.
    But, all my business classes have the same Sequence Name: "ID_SEQ" then, when I start running my JE BDB at first time, I start saving 3 new Department objects and the sequence for these department objects star with "#1" and finishes with #3.
    Then I continue saving Employee objects (here was the problem) I thought that my next Sequence number could be #4 but actually it was #101 so when I tried to save my very first Employee, I set the property "managerId=null" since this employee is the Manager, then, when I tried to save my second Employee who is working under the first one (the manager employee), I got the following exception message:
    TryingJEBDBApp DatabaseExcaption: com.sleepycat.je.ForeignConstraintException: (JE 4.0.71) Secondary persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee#*managerId*
    foreign key not allowed: it is not present in the foreign database
    persist#EntityStoreName#com.dmp.gamblit.persistence.BDB.store.eployee.Employee
    The solution:
    I fixed it modifying the managerId value from "4" to "101" and it works now!
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...
    Have you any good material about these topics, perhaps a link where I can find more detailed information on these?
    Thanks in advance Mark, thanks for your attention on this and I will post more doubts in the future for sure ;0)
    Regards,
    Diego

    Hi Diego,
    I fixed it modifying the managerId value from "4" to "101" and it works now!I'm glad you found the problem. It is usually best to get the assigned ID from the entity object after you call put(), and then use that value to fill in related fields in other entities. The primary key field (assigned from the sequence) is set by the put() method.
    At this moment I'm trying to understand the Sequence mechanism and refining concerns about Cursors manipulation...Have you any good material about these topics, perhaps a link where I can find more detailed information on these? >
    To find documentation, start at the first message in the forum, the Welcome message:
    http://forums.oracle.com/forums/ann.jspa?annID=250
    This refers to the main JE doc page, the JE FAQ and a white paper on DPL queries. The FAQ has a section on the DPL, which refers to the javadoc. The DPL javadoc has lots of info on using cursors along with indexes (see EntityIndex, PrimaryIndex, SecondaryIndex). The white paper will be useful to you if you're accustomed to using SQL.
    I don't know of any doc on sequences other than the javadoc:
    http://www.oracle.com/technology/documentation/berkeley-db/je/java/com/sleepycat/persist/model/PrimaryKey.html#sequence()
    This doc will point you to info on configuring the sequence, if that's what you're interested in.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Private - encapsulation or inheritance (but not both)

    Suppose that your class has some internal computation or logic that it performs, and that you wish to encapsulate this in a method that can not be called by other classes.
    You provide public methods that filter, format, or somehow modify the input and/or output of this encapsulated method.
    class pseudoCodeClass {
    private coreLogic(Objects inputs) {
    Maybe some complicated math stuff;
    Or password stuff;
    Or pay out functionality for a slot machine;
    return(stuff);
    public getUserData(inputs) {
    format/check the inputs;
    coreLogic(inputs);
    format the output;
    Now, how do you leveradge the power of OO inheritance to extend the internal logic that you encapsulated? If you make the interal logic private, then it's encapsulated, but you lose the power of OO inheritance, or you can make it protected and lose the encapsulation. I thought an OO language was supposed to have encapsulation and inheritance, not encapsulation or inheritance. (And, yes I realize that there is some techincal sense in which private methods are still inherited, but I'm talking about the general OO concept of inheritence where it includes overriding or extending.)
    Suppose you want to:
    class pseudoCodeSubclass extends pseudoCodeClass {
    private coreLogic(inputs) {
    super.coreLogic(inputs);
    additional more specific code; // The whole point of OO inheritence
    You can't extend super.coreLogic through your access to super.getUserData because it does all sorts of filtering and formating that is not a part of the internal logic that you wish to extend/override. And, providing other more public accessor methods to the core logic just defeats the encapsulation.
    I have seen many discussions of this, but none with any answers to my satisfaction. One line of answers is that you don't want encapsulated stuff to be part of your object's contract. Some times people with this sort of answer even suggest coppying the code from the super class into the subclass. People with this sort of answer don't seem to even want the option to use inheritence because of the obligation that might go with it. But without the option of inheriting encapsulated logic, they are forced to either use cut and paste (in an OO language that seems wrong to me) or to abandon encapsulation all together. Being forced into those 2 extreems doesn't seem to me like it would simplify future support of your class, and future support seems to be the primary point of the contract line of response.
    The way some people argue about this, I amost want to say - Look! In C you can encapsulate everything you want, and never have to worry about inheritance. (But you still shouldn't have to cut and paste.)
    Another line of response that I have seen is that private methods should only be used in breaking up code that would have gone into a single method. In other words, the private methods aren't really 'units of program logic' they are just a mater of organizational convenience. So if you had:
    public oneBigMessyMethod() {
    100 lines of A;
    100 lines of B;
    100 lines of C;
    you could maintain it as:
    public oneBigMessyMethod() {
    a();
    b();
    c();
    private a() {
    100 lines of A;
    private b() {
    100 lines of B;
    private c() {
    100 lines of C;
    I agree private works well in this situation. Presumably since a(), b() and c() are divided up for convenience rather than because of distinct logical function, you wouldn't want to extend just a() with inheritance. But this also seems to dodge the question. Just because sometimes you might not want encapsulated functionality to be available for extention, does not mean that you would never want it. I think that I'd also have to disagree with the permise that encapsulation is only for hiding stuff that is just a convention of convenience. The main point of encapsulation is to hide information or functionality. If encapsulation is only used for the convenient breakdown of your primary functionality, then all of your primary functionality is public, package or protected. That does make it inheritable. But, now all of the primary functionality is a part of the contract for that class.
    Is there an answer to this issue that does not ignore the value of either encapsulation or inheritance?
    There is one way that I can see to do exactly what I think should be possible. That is to put only classes from the same hierarchy in a package. Then both package and protected effectively provide encapsulation with the ability to inherit (and you do still have the option to use private or final if there is a case where you want to disable inheritence).
    What I'd like to know is - What do people actually do? In the real world, do people:
    1) use private + cut and paste
    2) use package/protected + self discipline
    Where 2 is that you drop encapsulation within your package but then excercise self dicipline and just don't call/access stuff that you intend to be for that class only...
    Or is there some 3rd thing that I'm missing? I've tried to think how maybe you could design your objects in such a way that you'd never need to inherit/extend something that you would also want to encapsulate. But I just don't see how that's possbile.
    So, what do people do?
    Chris

    First of all, you have got to understand that I am not
    suggesting that Private and Final should be changed or
    removed from java. It looks to me like there should
    be an additional access option (and there was
    originaly).
    I understand that if a class inherits something, it
    could expand the access or put public accessor methods
    around it. Obviously with ultra sensitive code this
    would be a nightmare. So private and final are very
    important. But if the very possibility of another
    class expanding a given level of access is a reason
    for not even having that level of access, then why do
    we have package and protected?
    There are a great number of places in common coding where that access does restrict usage in a usable way.
    >
    If the only re-use of your code that you allow is
    through the public interface, what do you even need an
    OO language for? Just for the polymorphism and a
    different way to organize your code?
    Not sure what you mean by that but see below.
    But as I've said. I've seen this whole thing argued a
    number of times. But what I haven't seen is any
    explanation of what people who take the poslition that
    I'm taking actually do when they write code. Because
    I can sit here with a bunch of other people and say 'I
    wish Java had this or that'. And then of couse a
    bunch of people will resopond and say 'no that's dumb'
    or 'I don't see the point'. But at the end of the
    day, Java still is what it is. So, arguing about what
    it 'should be' is not going to effect how anyone
    codes.
    Sure it can. That is why java now has assert().
    So, what I started out wanting to know is how people
    actually code. Particularly people who wish that Java
    had a subclass only access modifier.
    I don't wish that.
    Perhapse I should also be asking about how things are
    done by people who see this level of access as
    unnececary. How they code is easy enough to
    understand. Making everything that is not intended to
    be accessed by any other class private is easy enough
    to do. But what would be interesting to know is how
    do you design your classes to leveradge inheritance if
    you do this. Maybe there is some way of desinging
    around ever having 'internal functionality' that you
    would want to extend and I'm just not getting it.
    There are three broad classifications of objects.
    1. Those that only use encapsulation
    2. Correct inheritence hierarchies
    3. Incorrect inheritence hierarchies
    The first of those, which I consider most classes to fall into, do not need this.
    The third area occurs when programmers use inheritence as a convenience mechanism to propogate behavior amoung different classes rather than using encapsulation as should be done. They don't understand the difference between "is-a" relationships (design) and coding convienence. I would estimate that at least 50% of existing object hierarchies fall into this area. Since in this case the entire design is wrong an extension is not needed.
    The second area is the only correct area where this might be needed. Since I personally believe that very few classes belong in hierarchies and this proposed extension would only be useful in a sub fraction of those. Since the correct usage is so small I don't think it would be useful addition to the language.

  • Can java have Protected or Private Constructor

    Hi,
    can java have Priavte or protected constructor,
    as we know java have default and public constructor ,
    and in using singleton design patters we can use private & protected constructor,
    so, what is the main logic,
    Regards,
    Prabhat

    Hi,
    Yes, We can declare constructor as private/public/protected also.
    Having only private constructors means that you can't instantiate the class from outside the class (although instances could still be created from within the class - more about this later). However, when you instantiate a class, you must first initialize all superclasses of that class by invoking their constructors. If one of the superclasses has only private constructors declared, we have a problem. We can't invoke the superclass' constructor which means that we can't instantiate our object. Because of this, we've essentially made a class that can't be extended.
    example:
    class TheWorld
    private static TheWorld _instance = null;
    private TheWorld() {}
    public static TheWorld instance()
    if ( _instance == null )
    _instance = new TheWorld();
    return _instance;
    public void spin() {...}
    public class WorldUser
    public static void main(String[] args)
    TheWorld.instance().spin();
    }

  • Private inner class with private constructor

    I read that if constructor is public then you need a static method to create the object of that class.
    But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
    I am messing with this concept.
    public class Test {
          public static void main(String[] args) {          
               Test t = new Test();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    * Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
    Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
    eg:
    class ImInTheSameSourceFileAsInnerAccessTest {
        public static void main(String[] args) {          
            InnerAccessTest t = new InnerAccessTest();
            InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    public class InnerAccessTest {
          public static void main(String[] args) {          
               InnerAccessTest t = new InnerAccessTest();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }Result:
    $ javac -d bin src/InnerAccessTest.java
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    2 errors
    Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file'

  • Private constructor documented as public by javadoc

    I'm generating document for a class similar to the following:
    public class Example {
    public static final Example TYPE1 = new Example();
    public static final Example TYPE2 = new Example();
    private Example() {
    // private constructor
    When I run the Javadoc tool on this class, it lists the constructor as being public, which it is not! Is this a bug in javadoc, or am I doing something wrong?

    I think I can explain it.
    I would bet you first created the class without any constructor
    and ran Javadoc on it.
    In that case, not only does javac create a public default
    no-arg constructor, but javadoc also documents that constructor,
    even though it's not present in the source file.
    Later, when you added the private constructor, that prevented
    the default constructor from being automatically created.
    This is documented at:
    http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#16823
    BTW, we consider relying on default constructors as poor programming
    practice, as described at:
    http://java.sun.com/j2se/javadoc/writingdoccomments/index.html#defaultconstructors
    -Doug Kramer
    Javadoc team

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

Maybe you are looking for

  • BDC Problem in Smartforms

    How do we capture expansion of sub-items in BDC recording? Here's my original task: I have to change the dimensions of a window which is common in around 200 smartforms. I can change the forms manually as well, but I want to write a BDC. Here's the r

  • G50-70: empty DVD-drive clicking and freezing other drives for about 30 seconds all the time

    Hello board. Big problem. Seem to be the only one having this after searching the board: Brand new G50-70: When using OS from the SSD or using OS from the SSD and doing things with a USB-drive, the empty internal DVD-drive making clicking sound and s

  • Mapping an irregular shape to represent monitor screen

    Hi everyone, I have captured movements inside an irregular shape and need to map it on the monitor's screen. The input space is a 2D shape with 4 boundaries and these boundaries are not straight lines but irregular and nonlinear. The 2nd space is sim

  • Will i lose any work i have done if i stop using elements 6 and use 4

    i have elements 4 but am trying out a trial version of 6 i have edited some photos and also tagged them if i dont buy 6 and my trial finishes what will happen to any work i have done when i start using 4 again? also is there any video help on using 4

  • How to test whether a table exists in database?

    How can I test whether a table exists in a database before I execute a query? If the table doesn't exist, I want first create a default table with certain name so that I can always display something in JTable. Thanks!