A little question about inheritance

Can someone explain this to me?
I have been reading about inheritance in Java. As I understand it when you extend a class, every method gets "copied" to the subclass. If this is so, how come this doesn't work?
class inherit {
    int number;
    public inherit(){
        number = 0;
    public inherit(int n){
        number = n;
class inherit2 extends inherit{
    public inherit2(int n, int p){
        number = n*p;
class example{
    public static void main(String args[]){
        inherit2 obj = new inherit2();
}What I try to do here is to extend the class inherit with inherit2. Now the obj Object is of inherit2 class and as such, it should inherit the constructor without parameters in the inherit class or shouldn't it ??? If not, then should I rewrite all the constructors which are the same and then add the new ones??

I believe you were asking why SubClass doesn't have the "default" constructor... after all, shouldn't SubClass just have all the contents of SuperClass copy-pasted into it? Not exacly. ;)
(code below... if you'd like, you can skip the first bit, start at the code, and work your way down... depending on if you just started, the next bit may confuse rather than help)
Constructors are special... interfaces don't specify them, and subclasses don't inherit them. There are many cases where you may not want your subclass to display a constructor from it's superclass. I know this sounds like I'm saying "there are many cases where you won't want a subclass to act exactly like a superclass, and then some (extend their functionality)", but its not, because constructors aren't how an object acts, they're how an object gets created.
As mlk said, the compiler will automatically create a default constructor, but not if there is already a constructor defined. So, unfortunatley for you, there wont be a default constructor made for SubClass that you could use to create it.
class SuperClass { //formerly inherit
int number;
public SuperClass () { //default constructor
number = 0;
public SuperClass (int n) {
number = n;
class SubClass extends SuperClass { //formerly inherit2
//DEFAULT CONSTRUCTOR, public SubClass() WILL NOT BE ADDED BY COMPILER
public SubClass (int n, int p) {
number = n*p;
class Example {
public static void main(String [] args) {
//attempted use of default constructor
//on a default constructorless subclass!
SubClass testSubClass = new SubClass();
If you're still at a loss, just remember: "Constructors aren't copy-pasted down from the superclass into the subclass!" and "Default constructors aren't added in if you add your own constructor in" :)
To get it to work, you'd have to add the constructor you used in main to SubClass (like doopsterus did with inheritedClass), or use the constructor you defined in SubClass for when you make a new one in main:
inherit2 obj = new inherit2(3,4);
Hope that cleared things up further, if needed. By the way, you should consider naming your classes as a NounStartingWithACapital, and only methods as a verbStartingWithALowercase

Similar Messages

  • One very basic question about inheritance

    One very basic question about inheritance.
    Why we need inheritance?
    the benefit of inheritance also achieve by creating instance of base class using it in other class instead of extending the base class.
    Can any one please explain why we are using inheritance instead of creating object of base class????

    SumitThokal wrote:
    One very basic question about inheritance.
    Why we need inheritance?
    the benefit of inheritance also achieve by creating instance of base class using it in other class instead of extending the base class.
    Can any one please explain why we are using inheritance instead of creating object of base class????What did you find out when you looked on Google?
    One example of inheritance comes in the form of a vehicle. Each vehicle has similarities however they differ in their own retrospect. A car is not a bus, a bus is not a truck, and a truck is not a motorbike. If you can define the similarities between these vehicles then you have a class in which you can extend into either of the previous mentioned vehicles. Resulting in a reusable class, dramatically reduces the size of code, creates a single point of definition, increases maintainability, you name it.
    In short there are thousands of benefits from using inheritance, listing the benefits could take a while. A quick Google search should give you a few hundred k if not million links to read.
    Mel

  • Two little questions about ROWID

    Hello friends at www.oracle.com ,
    as we know, each time we insert a new line, Oracle creates an unique ROWID for that line. I have 2 questions about ROWID:
    1. Is there a way for me to obtain ROWID value at the moment of insertion, other than doing a SELECT rowid FROM (table) WHERE (primary key inserted values) to obtain the ROWID that was generated for that line?
    2. If, for any reason, we have a so big database that all ROWID possible combinations are over, how would Oracle handle such situation? I believe it's something quite rare to happen but, anyway, there's the possibility as Murphy Laws have taught us :)
    Thanks for all answers, and best regards,
    Franklin Gongalves Jr.

    1. The (quite new) DML RETURNING clause allwos this:
    Eg. insert into bonus values ('Bill', 'work',100, 4) returning rowid into :x
    This works in 8.1.7 and 9.0.1 I don't know about earlier.
    2. A rowid includes the physical address of the data. Before you used all the rowid's, the database wouldn't be able to hold any more data. The limit is big, but not infinite. If you hit it, try going to distributed databases using database links.

  • A question about inheritance and overwriting

    Hello,
    My question is a bit complicated, so let's first explain the situation with a little pseudo code:
    class A {...}
    class B extends A{...}
    class C extends B {...}
    class D extends C {...}
    class E extends B {...}
    class F {
      ArrayList objects; // contains only objects of classes A to E
      void updateObjects() {
        for(int i = 0; i < objects.size(); i++)
          A object = (A) objects.get(i); // A as superclass
         update(A);
      void update(A object) { ... }
      void update(B object) { ... }
      void update(D object) { ... }
    }My question now:
    For all objects in the objects list the update(? object) method is called. Is it now called with parameter class A each time because the object was casted to A before, or is Java looking for the best fitting routine depending on the objects real class?
    Regards,
    Kai

    Why extends is evil
    Improve your code by replacing concrete base classes with interfaces
    Summary
    Most good designers avoid implementation inheritance (the extends relationship) like the plague. As much as 80 percent of your code should be written entirely in terms of interfaces, not concrete base classes. The Gang of Four Design Patterns book, in fact, is largely about how to replace implementation inheritance with interface inheritance. This article describes why designers have such odd beliefs. (2,300 words; August 1, 2003)
    By Allen Holub
    http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html
    Reveal the magic behind subtype polymorphism
    Behold polymorphism from a type-oriented point of view
    http://www.javaworld.com/javaworld/jw-04-2001/jw-0413-polymorph_p.html
    Summary
    Java developers all too often associate the term polymorphism with an object's ability to magically execute correct method behavior at appropriate points in a program. That behavior is usually associated with overriding inherited class method implementations. However, a careful examination of polymorphism demystifies the magic and reveals that polymorphic behavior is best understood in terms of type, rather than as dependent on overriding implementation inheritance. That understanding allows developers to fully take advantage of polymorphism. (3,600 words) By Wm. Paul Rogers
    multiple inheritance and interfaces
    http://www.javaworld.com/javaqa/2002-07/02-qa-0719-multinheritance.html
    http://java.sun.com/docs/books/tutorial/java/interpack/interfaceDef.html
    http://www.artima.com/intv/abcs.html
    http://www.artima.com/designtechniques/interfaces.html
    http://www.javaworld.com/javaqa/2001-03/02-qa-0323-diamond_p.html
    http://csis.pace.edu/~bergin/patterns/multipleinheritance.html
    http://www.cs.rice.edu/~cork/teachjava/2002/notes/current/node48.html
    http://www.cyberdyne-object-sys.com/oofaq2/DynInh.htm
    http://www.gotw.ca/gotw/037.htm
    http://www.javajunkies.org/index.pl?lastnode_id=2826&node_id=2842
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=1&t=001588
    http://pbl.cc.gatech.edu/cs170/75
    Downcasting and run-time
    http://www.codeguru.com/java/tij/tij0083.shtml
    type identification
    Since you lose the specific type information via an upcast (moving up the inheritance hierarchy), it makes sense that to retrieve the type information ? that is, to move back down the inheritance hierarchy ? you use a downcast. However, you know an upcast is always safe; the base class cannot have a bigger interface than the derived class, therefore every message you send through the base class interface is guaranteed to be accepted. But with a downcast, you don?t really know that a shape (for example) is actually a circle. It could instead be a triangle or square or some other type.
    To solve this problem there must be some way to guarantee that a downcast is correct, so you won?t accidentally cast to the wrong type and then send a message that the object can?t accept. This would be quite unsafe.
    In some languages (like C++) you must perform a special operation in order to get a type-safe downcast, but in Java every cast is checked! So even though it looks like you?re just performing an ordinary parenthesized cast, at run time this cast is checked to ensure that it is in fact the type you think it is. If it isn?t, you get a ClassCastException. This act of checking types at run time is called run-time type identification (RTTI). The following example demonstrates the behavior of RTTI:
    //: RTTI.java
    // Downcasting & Run-Time Type
    // Identification (RTTI)
    import java.util.*;
    class Useful {
    public void f() {}
    public void g() {}
    class MoreUseful extends Useful {
    public void f() {}
    public void g() {}
    public void u() {}
    public void v() {}
    public void w() {}
    public class RTTI {
    public static void main(String[] args) {
    Useful[] x = {
    new Useful(),
    new MoreUseful()
    x[0].f();
    x[1].g();
    // Compile-time: method not found in Useful:
    //! x[1].u();
    ((MoreUseful)x[1]).u(); // Downcast/RTTI
    ((MoreUseful)x[0]).u(); // Exception thrown
    } ///:~
    As in the diagram, MoreUseful extends the interface of Useful. But since it?s inherited, it can also be upcast to a Useful. You can see this happening in the initialization of the array x in main( ). Since both objects in the array are of class Useful, you can send the f( ) and g( ) methods to both, and if you try to call u( ) (which exists only in MoreUseful) you?ll get a compile-time error message.
    If you want to access the extended interface of a MoreUseful object, you can try to downcast. If it?s the correct type, it will be successful. Otherwise, you?ll get a ClassCastException. You don?t need to write any special code for this exception, since it indicates a programmer error that could happen anywhere in a program.
    There?s more to RTTI than a simple cast. For example, there?s a way to see what type you?re dealing with before you try to downcast it. All of Chapter 11 is devoted to the study of different aspects of Java run-time type identification.
    One common principle used to determine when inheritence is being applied correctly is the Liskov Substitution Principle (LSP). This states that an instance of a subclass should be substitutible for an instance of the base class in all circumstances. If not, then it is generally inappropriate to use inheritence - or at least not without properly re-distributing responsibilities across your classes.
    Another common mistake with inheritence are definitions like Employee and Customer as subclasses of People (or whatever). In these cases, it is generally better to employ the Party-Roll pattern where a Person and an Organization or types of Party and a party can be associated with other entities via separate Role classes of which Employee and Customer are two examples.

  • A little question about the WWDC 2006 and Macbook

    I was considering to buy my first Macbook, no, my first mac EVER these days, but after i heard of the WWDC 2006 i'm afraid to miss some new upgrades made on the Macbook when i buy it next week.
    But someone told me too, that even if there are Upgrades, i probably have to wait them to come to Europe for about 2 month - and thats much to long to wait for me cause i need it for work in the next four weeks !
    Hope you can say me whats to do
    Greetings
    Agent Darkbooty

    Thank you very much for your help
    But i've got still a question ..
    ..would you buy the macbook next week or would you wait untill the end of the conference ?
    Seems like there will only be software updates for the macbook

  • A Little question about Pixel Aspect Ratio

    This doubt has been bugging me since I started edit HD formats.It's about pixel aspect ratio.
    Let's supose I have received some material in HD format,for instance.But I will deliver this material in another format, DV NTSC,for instance.
    The Pixel aspect ratio format of the material what I received and the way how I will deliver are different.What can I do to avoid this problem? Do I need to apply some plugin to solve this problem or when I export the final sequence Final Cut does this automatically?
    thank you

    The software takes care of it for you.
    As long as your conversion maintains the overall aspect ratio (ie 16:9), it is irrelevant what the individual pixels are doing.
    For example, if I convert DVCProHD 720p to ProRes 720p, it will look fine even though the DVCProHD started out with 960 pixels in the x dimension and the ProRes will have 1280.
    x

  • A little question about graphs

    Hello,
    I took an example which already exists in the Ni repertoire, and I modify it according to what I have need.
    My question is Dynamic Induction.vi excecute and stops after 3000seconds, I will want that if I click on the button "Stop", the tracing of the curves stops immediately. How do I have to make in this case? I thank you in advance.
    I send you the differents files.
    Attachments:
    Dynamic Induction Motor.zip ‏444 KB

    Hello,
    I thank you much for your assistance. I thus modified Dynamic InductionMOD.vi consequently.
    I have another question, how do I have to make to safeguard the curves posted in a file so that I can use them at the time of the next excécution of the VI?
    Another question, how do I have to make to just be able to copy some curves posted to put them for example in a written report of Word file?
    Is it possible to be able to print using a printer right a graph, for example a "Torque vs time" contained in the graphe1? How do I have to proceed?
    I send the new modified files to you
    I thank you in advance for your assistance.
    With soon!!
    Nadine
    Attachments:
    Dynamic Induction Motor.llb ‏896 KB

  • Question about inheritance

    I'm attempting to write Monopoly and I'm having some inheritance problems. Every space on the board is first and foremost of type BoardSpace however some of them are of type Property which extends BoardSpace and some are of type Chance/Community which also extend BoardSpace etc. Depending on what type of space it is something different happens. Right now heres how a couple of classes look. I'm having a problem where if I land on a space that doesn't define its own action method, it defaults to the BoardSpace action method as it should yet it goes into that if statement even when it clearly shouldn't be. Like if I land in jail, it will still go into that if statement, and it will print Jail (3 times). Is this something funky with inheritance?
    BoardSpace:
    public class BoardSpace extends JPanel
         Location loc;
         String name;
         public BoardSpace(String s, Location l)
              loc = l;
              name = s;
         public void action(Player p)
              if(name.equals("Go"));//If name is "go" how can it also be "jail" ?
                   System.out.println(name);
                   System.out.println(this.name);
                   System.out.println(p.spot.name);
                   p.money+=200;
    }Property:
    import javax.swing.*;
    public class Property extends BoardSpace
         Player owner = null;
         public Property(String s, Location l)
              super(s,l);
         public void action(Player p)
              if(owner!=null && owner!=p)
                   JOptionPane.showMessageDialog(this,"You landed on "+this.name+".\n This property is owned by Player" +owner.number+".\n You owe $5");
              else
                   JOptionPane.showInputDialog("Buy?");
    }

    duckbill wrote:
    Hint: you can launch JOptionPane dialogs without a single panel, frame etc...
    #You can also launch dialogs with panels, frames, etc... but without subclassing Property from JPanel
    Edited by: DrLaszloJamf on Oct 3, 2007 12:42 PM

  • One little question about searching partial text in object name

    Hello Everyone,
    I have searched a bit but couldn't find an answer about this.
    I am a Freehand user and i am currently using navigation names for differents items. Works perfectly good.
    But now i need to search part of the items name.
    For example i have the objects named in the nabigation panel as:
    - "ItemA-rotation" for the first group of items
    - "ItemB-static" for the second group of items
    as for now i can search for all the items A by typing in the search graphic panel "ItemA-rotation" but i would like to find both item A and B by typing a unique search request.
    Is it possible to write something like: "*Item*" to search every items that contains the part "Item" in the full name ?
    Thank you for your future answers.
    Cheers.
    PS: i am using Mac os X with Freehand MX.

    It appears it isn't possible. I set up a similar document with spaces added between the word "index" and the letters "A" or "B". My thinking was that the connected wording of your phrase "ItemA-rotation" was limiting the search. But searching for the word "index" didn't reveal all the items; it had to be typed exactly as the name was set up in the Navigation Panel. Perhaps I'm missing some unknown control characters but I have never seen what those could be.

  • Little question about Newsstand.

    Just wondering why nothing in the free section of Newsstand is free? I'd like to at least get one or two magazines or articles about things I enjoy for free. Maybe something to think about, Apple.

    So you can use xml to create and load items into dynamic
    movieclips so you can see this one to itroduct yourself to xml
    http://www.kirupa.com/web/xml/XMLwithFlash3.htm
    or the other and easy way is to use Treww component and see how it
    works in Flash samples in your computer \Program
    Files\Macromedia\Flash 8\Samples and
    Tutorials\Samples\ActionScript\Galleries\ and see the Gallery_Tree
    if you want you can see the Gallery_Tween this files is for gallery
    but u can transofrm easy to use for your project cheers :))

  • Question about inheritance and  casting

    according to the java api it said Calendar() is a super-class of GregorianCalendar(). with that said it means GC inherits all members of C(). i hope everyone agrees with me here.
    why is it necessary to do this:
    Calendar c = new GregorianCalendar();//by the way this is called implicit casting per the java tutorial.if GC inherits everything from C, and if you need members from both classes, then wouldn't it be enough to just do
    GregorianCalendar gc = new GregorianCalendar();why is it necessary to declare a variable of the parent class and assign a subclass reference to that variable?

    then why does the tutorial show this?Why not? It's legal Java. It's what I would probably write, unless I knew I was going to use some methods that were in GregorianCalendar and not in Calendar.

  • A little question about the pencil tool

    I have just a tiny guestion about the pencil tool in illustrator.
    When i want to draw like it is a real pencil and make a lot of lines with it, then everytime when i'm drawing lines are disappearing because i'm drawing it again.
    Maybe thats because i'm drawing over the other lines...but is there a simple way to make new lines all the time, so i can draw a bunch of lines over each other and agross etc.
    hope you understand my crappy english.
    with love,
    Linda

    Double click the pencil tool icon and check the options. You won't want to "edit selected paths"

  • Little question about a Claws-Mail tray icon theme, and how to use it.

    There is a Claws Mail tray icon theme available on gnome-look.org:
    http://gnome-look.org/content/show.php/ … tent=71540
    These are the instructions the author gives to install the theme:
    Claws Mail Tango trayicon theme
    Claws-Mail version = 3.3.0
    copy icons claws-mail-3.3-0/src/pixmaps, recompile and install.
    So what am I supposed to do (especially since the newest Claws Mail version is 3.4.0...)?

    Stalafin wrote:
    There is a Claws Mail tray icon theme available on gnome-look.org:
    http://gnome-look.org/content/show.php/ … tent=71540
    These are the instructions the author gives to install the theme:
    Claws Mail Tango trayicon theme
    Claws-Mail version = 3.3.0
    copy icons claws-mail-3.3-0/src/pixmaps, recompile and install.
    So what am I supposed to do (especially since the newest Claws Mail version is 3.4.0...)?
    I would recommend using ABS. just makepkg -o first so the sources get DL'd and unpacked. copy your icons and makepkg -e so the sources are not extracted again and therefore your new icons overwitten.
    finally, enjoy some awesomeness:

  • A little question about compiling my own kernel

    Hii, How can I know please, wich moudle is loaded in my current kernel and being used?
    for example, if I have now the RAID xxxx , and I don't use it, so when compiling my own Kernel, I don't need it.
    How can I know wich ones arn't needed?

    Ok Lsmod I know, is there any thing else?

  • Quick question about inheritance and exceptions

    If I have two classes like this:
    public class ClassA {
        public void myMethod() throws NumberFormatException {
          throw new NumberFormatException();
    public class ClassB extends ClassA {
        public void myMethod() {
    }Does myMethod() in classA override myMethod in classB?
    And why?
    Thank you,
    V

    I just want to add that since NumberFormatException is
    a descendant of RuntimeException, you are not required
    to declare that the method throws this exception. Some
    people think it is a good idea to declare it anyway
    for clarity. Personally, I don't think so.I agree.
    I think Sun recommends that you don't declare unchecked exceptions in the method declaration, but do document them in the javadoc comments.

Maybe you are looking for