1 2 Previous Next 18 Replies Latest reply: Jun 5, 2012 3:53 PM by jschellSomeoneStoleMyAlias RSS

    Base class initialization

    Prem
      Hi All ,

      I have one doubt,

      When I have following relationship
      class Base{
           
           public Base(){
                System.out.println("Base Class");
           }
           
           public void method() {
                System.out.println("in Base method");
           }
           
      }
      
      class SubClass extends Base{
           
           public SubClass() {
                System.out.println("SubClass ");
           }
           
           @Override
           public void method() {
                System.out.println("In SubClass method");
           }
      }
      
      
      public class TestInheritance {
           
           
           public static void main(String[] args) {
                
                Base base = new SubClass();
                base.method();
                
           }
      
      }
      In above example , Though I am creating object of subclass, Base class object is also get created .. I mean I have already overridden method of Base Class so why Base class's object is being created ? Any advantage ?

      And If it is get created does that mean if I have long hierarchy tree of inheritance , whatever class in that tree JVM will create object of each class ?


      Please correct me if I am wrong....

      Edited by: Prem on May 26, 2012 5:08 AM
        • 1. Re: Base class initialization
          EJP
          why Base class's object is being created?
          Because that's what it means to extend a base class. If you don't want that, don't extend it.
          Any advantage?
          A meaningless question. That is how the language is defined. It is how inheritance is defined in all languages with inheritance as far as I know.
          And If it is get created does that mean if I have long hierarchy tree of inheritance , whatever class in that tree JVM will create object of each class ?
          All base classes are created. I'm not sure if that answers this question as I can barely make sense of it.
          • 2. Re: Base class initialization
            Prem
            Any advantage?
            A meaningless question. That is how the language is defined. It is how inheritance is defined in all languages with inheritance as far as I know.
            But Can you explain how memory is going to be utilized in effeicient manner ? If I dnt require base object , what it is going to be created ?
            • 3. Re: Base class initialization
              EJP
              But Can you explain how memory is going to be utilized in effeicient manner?
              No. Why do you ask? I don't understand the relevance of the question.
              If I dnt require base object, what it is going to be created?
              I don't understand that question either. 'What it is going to be created' is meaningless. Please restate in standard English.

              And when people ask you what you mean, answer them.

              Your questions are basically futile. I repeat. If you don't require the base object, don't extend the base class.
              • 4. Re: Base class initialization
                Prem
                EJP wrote:
                But Can you explain how memory is going to be utilized in effeicient manner?
                No. Why do you ask? I don't understand the relevance of the question.
                Calm down EJP:) I just wanted to clear my concepts. What I thought is that , when I create an object of subclass , I guess , only that much of memory should be allocated required for to instantiate that object. If Parent's object is created then that memory may be wasted , right ?

                Point is when from any method of subclass , when I hit super.baseMethod() at that time only JVM should load super class because at this moment I need it . right ?

                I am just trying to clear my concepts over here . I am not encouraging any one to reply me . If you fill that this question is invalid then ignore this .
                • 5. Re: Base class initialization
                  796440
                  Prem wrote:
                  EJP wrote:
                  But Can you explain how memory is going to be utilized in effeicient manner?
                  No. Why do you ask? I don't understand the relevance of the question.
                  Calm down EJP:) I just wanted to clear my concepts. What I thought is that , when I create an object of subclass , I guess , only that much of memory should be allocated required for to instantiate that object. If Parent's object is created then that memory may be wasted , right ?
                  No, it's not wasted. It's allocated because you need it. If you didn't need it, you wouldn't have declared the child class to extend that base class. And if you didn't need it but you declared it as a subclass of that class anyway, then you have a flawed design, so any memory being wasted is because you chose to waste it.
                  Point is when from any method of subclass , when I hit super.baseMethod() at that time only JVM should load super class because at this moment I need it . right ?
                  Wrong. While in theory it might have been possible to define the language that way, it would have added unnecessary complexity for no significant benefit.

                  And it just makes no sense logically. If I have Child extends Parent, then every instance of Child IS-A Parent. When I create a new Child object, I know that I am, by definition, also creating a Parent object. (It's a single object, but it IS-A Child and it IS-A Parent.) I expect it to be fully initialized to a valid state for a Parent and to a valid state for a Child. That means Parent's constructor will run before Child's constructor, and set Parent's member variables appropriately.
                  I am just trying to clear my concepts over here . I am not encouraging any one to reply me .
                  Wrong. By posting in a public forum, you are implicitly inviting anybody who reads your post to reply. If you don't like that, you'll need to make private arrangements with individuals you choose to answer your questions.
                  If you fill that this question is invalid then ignore this .
                  You don't get to decide that. If somebody feels the question is invalid, he has the right to tell you so.
                  • 6. Re: Base class initialization
                    ++sja
                    You may have a slight misunderstanding of how objects work when you say "parent's object is created".

                    There is no parent object. When you do "new SubClass()" only one object is created. Under the covers, in the Sun/Oracle JVM, an object has an object header, followed by fields declared in the object and its superclasses. On a 32-bit JVM, the object header is eight bytes. Since you declare no fields in either Base or SubClass, that is the full total size of the object.

                    Thus "new Base()" allocates eight bytes. "new SubClass()" also allocates eight bytes. "new Object()" is also eight bytes. There is no wasted memory, and there is no "parent object".

                    If Base had a field, say "int foo;" then another four bytes would be needed to hold that field. "new Base()" would reserve 12 bytes, and "new SubClass()" would also be 12 bytes. That extra four bytes for the int would be needed by objects of either class, because if you declare a field, you get a field (duh!) Even if you didn't use "foo" it would still be allocated, as compilers and runtimes are not (at present) clever enough to optimize away unused fields.
                    • 7. Re: Base class initialization
                      796440
                      sja wrote:
                      You may have a slight misunderstanding of how objects work when you say "parent's object is created".

                      There is no parent object. When you do "new SubClass()" only one object is created. Under the covers, in the Sun/Oracle JVM, an object has an object header, followed by fields declared in the object and its superclasses. On a 32-bit JVM, the object header is eight bytes. Since you declare no fields in either Base or SubClass, that is the full total size of the object.

                      Thus "new Base()" allocates eight bytes. "new SubClass()" also allocates eight bytes. "new Object()" is also eight bytes. There is no wasted memory, and there is no "parent object".

                      If Base had a field, say "int foo;" then another four bytes would be needed to hold that field. "new Base()" would reserve 12 bytes, and "new SubClass()" would also be 12 bytes. That extra four bytes for the int would be needed by objects of either class, because if you declare a field, you get a field (duh!) Even if you didn't use "foo" it would still be allocated, as compilers and runtimes are not (at present) clever enough to optimize away unused fields.
                      Most of that is implementation-specific and not really relevant.

                      The key points are that a) A single object is created, b) It IS-A Parent and it IS-A Child, c) It has all the fields from both objects, and d) There is no waste unless the programmer introduced it by a flaw in his class hierarchy design.
                      • 8. Re: Base class initialization
                        EJP
                        What I thought is that , when I create an object of subclass , I guess , only that much of memory should be allocated required for to instantiate that object.
                        You have no basis for that belief.
                        If Parent's object is created then that memory may be wasted , right?
                        The question is meaningless. You wrote code that implies that the memory is allocated, so the memory is allocated. If you don't want it allocated, don't write that code. Any 'waste' was caused by the code you wrote.
                        Point is when from any method of subclass , when I hit super.baseMethod() at that time only JVM should load super class because at this moment I need it . right ?
                        Wrong. That's not how the language works. You can't just fantasize some arbitrary mode of operation and then say the language 'should' work that way. The language 'should' work the way it is defined to work. I suggest you would be better off learning Java than arguing about how you think it should work. Nothing you can say is going to change it.
                        I am just trying to clear my concepts over here. I am not encouraging any one to reply me.
                        That doesn't make any sense either. The only way you can 'clear your concepts' is by getting and reading replies. Otherwise the entire exercise is pointless. By posting here you are inviting replies. That is the purpose of these forums. Any forums.
                        If you fills that this question is invalid then ignore this.
                        If forum members feel your question is invalid they will say so. Nothing you can do about it. They are doing you a kindness by correcting your misconceptions.

                        This is a forum. You started a discussion thread: you are getting a discussion. You declared a base class: you get a base class. You may not like the logical consequences of your actions, but they're your actions.
                        • 9. Re: Base class initialization
                          Prem
                          This is a forum. You started a discussion thread: you are getting a discussion. You declared a base class: you get a base class. You may not like the logical consequences of your >actions, but they're your actions.
                          Here is a point that , you can keep replying by putting good thought in kind manner but seems that if some one like me ask something and in first attempt of reply the person like you without going to understand the point behind the question , simply writes some rude statement. did you directly started walking after your birth or it took some time for you to walk ?

                          My only advise to you is try to put statement in kind manner or point some link where someone can learn basic instead of saying "meaningless question ...."
                          • 10. Re: Base class initialization
                            EJP
                            simply writes some rude statement
                            I wrote no rude statements. I wrote an accurate description of your question. It remains accurate. It's not clear to me that you would recognize a 'good statement' when you saw one however it was presented. The evidence in this thread is against you.

                            Let's take another tack. Your derived class constructor calls super() implicitly, i.e. the base class constructor. At that moment the 'base object' has to exist. Let's also consider that the actual base class you are talking about contains no fields so has no visible memory cost at all. And let's also consider that if it did have fields, they would have to be initialized when its constructor was called. On all these grounds, there is no part of the 'base object' creation that could possibly be deferred. So once again your question fails to make sense. I don't know what makes you think you know more about language design than the guys who did design the language. You should rethink that assumption.
                            • 11. Re: Base class initialization
                              Prem
                              Hey EJP thanks for that knowledge ..

                              so you mean to say that base object exist .. but how can I check its existence ? Can you guide me on that...
                              • 12. Re: Base class initialization
                                796440
                                Prem wrote:
                                Hey EJP thanks for that knowledge ..

                                so you mean to say that base object exist .. but how can I check its existence ? Can you guide me on that...
                                Exactly ONE object exists. It IS-A Base and it IS-A Derived. You don't need to "check its existence." The JLS defines what you will get. If you don't believe the JLS, you can use the instanceof operator to verify that it IS-A Base and IS-A Derived.
                                • 13. Re: Base class initialization
                                  EJP
                                  @Prem What on earth is this thread about? You spend several posts complaining that an object is created 'too soon' and now you want to check its existence?

                                  The question is ridiculous. You create an object, all at once like you've been complaining about, it's created. No 'check' required.

                                  BTW don't tell people what they 'mean to say'. I already said what I meant to say. No translation required.
                                  • 14. Re: Base class initialization
                                    934982
                                    "Base class object is also get created "
                                    No, You just invoke the parent class 's constructor because SubClass is inherited from BaseClass.
                                    In your TestInheritance Class ,there is only a BaseClass reference (not object) ,you can invoke the method() ,
                                    but it is not from BaseClass ,it is from SubClass(you create an object of SubClass).

                                    So result will like :

                                    Base Class <-- parent Class constructor
                                    SubClass <-- this Class constructor
                                    In SubClass method <-- this Class method overrided)



                                    Ksharp
                                    1 2 Previous Next