Can any one explain how constructors, inheritance and run time polymorphism works ? Also explain logic behind the below outputUnderstanding prototypal inheritance in JavaScriptGoogle Gson - deserialize list<class> object? (generic type)Create the perfect JPA entityIs there an info-graphic that explains java variable inheritance and constructor code flow?Field access and Memory Allocation for Objects in Java PolymorphismIs it possible to write a program in Java without main() using JDK 1.7 or higher?Overriding private methods in (non-)static classesJava - Method executed prior to Default ConstructorJava applet error main method not foundjava exception - why does it catch?

How can glass marbles naturally occur in a desert?

Is it double speak?

Unexpected route on a flight from USA to Europe

Can chords be inferred from melody alone?

What is the German idiom or expression for when someone is being hypocritical against their own teachings?

12V lead acid charger with LM317 not charging

Our group keeps dying during the Lost Mine of Phandelver campaign. What are we doing wrong?

Does the United States guarantee any unique freedoms?

Can external light meter replace the need for push/pull?

Why do proponents of guns oppose gun competency tests?

What are these mathematical groups in U.S. universities?

Where to pee in London?

Differentiability of operator norm

Did Apollo leave poop on the moon?

Is there a drawback to Flail Snail's Shell defense?

How to halve redstone signal strength?

How to approach protecting my code as a research assistant? Should I be worried in the first place?

Can you use the Help action to give a 2019 UA Artillerist artificer's turret advantage?

Was Richard I's imprisonment by Leopold of Austria justified?

Does this smartphone photo show Mars just below the Sun?

How to help new students accept function notation

Is a switch from R to Python worth it?

Validation and verification of mathematical models

Why should public servants be apolitical?



Can any one explain how constructors, inheritance and run time polymorphism works ? Also explain logic behind the below output


Understanding prototypal inheritance in JavaScriptGoogle Gson - deserialize list<class> object? (generic type)Create the perfect JPA entityIs there an info-graphic that explains java variable inheritance and constructor code flow?Field access and Memory Allocation for Objects in Java PolymorphismIs it possible to write a program in Java without main() using JDK 1.7 or higher?Overriding private methods in (non-)static classesJava - Method executed prior to Default ConstructorJava applet error main method not foundjava exception - why does it catch?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I undertand the reason behind my output is run time polymorphism. But I am unable to figure it out how ?
Please Explain how run time polymorphism, constructors and inheritance are related.



This is JAVA code. I have triend understanding run time polymorphism but I have failed to figure it out.



package df;



class A1



A1()
System.out.println("Constructor A() called");

void m1()
System.out.println("Inside A's m1 method");





class B2 extends A1



B2()
System.out.println("Constructor B() called");


void m1()
System.out.println("Inside B's m1 method");





class C3 extends A1



C3()
System.out.println("Constructor C()");

void m1()
System.out.println("Inside C's m1 method");





public class Cldf



// object of type A 
public static void main(String[] args)
A1 a = new B2();






I expected result as below



Constructor B() called.



but result is



Constructor A() called
Constructor B() called










share|improve this question






























    0















    I undertand the reason behind my output is run time polymorphism. But I am unable to figure it out how ?
    Please Explain how run time polymorphism, constructors and inheritance are related.



    This is JAVA code. I have triend understanding run time polymorphism but I have failed to figure it out.



    package df;



    class A1



    A1()
    System.out.println("Constructor A() called");

    void m1()
    System.out.println("Inside A's m1 method");





    class B2 extends A1



    B2()
    System.out.println("Constructor B() called");


    void m1()
    System.out.println("Inside B's m1 method");





    class C3 extends A1



    C3()
    System.out.println("Constructor C()");

    void m1()
    System.out.println("Inside C's m1 method");





    public class Cldf



    // object of type A 
    public static void main(String[] args)
    A1 a = new B2();






    I expected result as below



    Constructor B() called.



    but result is



    Constructor A() called
    Constructor B() called










    share|improve this question


























      0












      0








      0








      I undertand the reason behind my output is run time polymorphism. But I am unable to figure it out how ?
      Please Explain how run time polymorphism, constructors and inheritance are related.



      This is JAVA code. I have triend understanding run time polymorphism but I have failed to figure it out.



      package df;



      class A1



      A1()
      System.out.println("Constructor A() called");

      void m1()
      System.out.println("Inside A's m1 method");





      class B2 extends A1



      B2()
      System.out.println("Constructor B() called");


      void m1()
      System.out.println("Inside B's m1 method");





      class C3 extends A1



      C3()
      System.out.println("Constructor C()");

      void m1()
      System.out.println("Inside C's m1 method");





      public class Cldf



      // object of type A 
      public static void main(String[] args)
      A1 a = new B2();






      I expected result as below



      Constructor B() called.



      but result is



      Constructor A() called
      Constructor B() called










      share|improve this question














      I undertand the reason behind my output is run time polymorphism. But I am unable to figure it out how ?
      Please Explain how run time polymorphism, constructors and inheritance are related.



      This is JAVA code. I have triend understanding run time polymorphism but I have failed to figure it out.



      package df;



      class A1



      A1()
      System.out.println("Constructor A() called");

      void m1()
      System.out.println("Inside A's m1 method");





      class B2 extends A1



      B2()
      System.out.println("Constructor B() called");


      void m1()
      System.out.println("Inside B's m1 method");





      class C3 extends A1



      C3()
      System.out.println("Constructor C()");

      void m1()
      System.out.println("Inside C's m1 method");





      public class Cldf



      // object of type A 
      public static void main(String[] args)
      A1 a = new B2();






      I expected result as below



      Constructor B() called.



      but result is



      Constructor A() called
      Constructor B() called







      java constructor polymorphism






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 27 at 5:21









      Abhilash LankaAbhilash Lanka

      1




      1

























          2 Answers
          2






          active

          oldest

          votes


















          0














          super() is by default called from the subclass when inheriting. This is done by the compiler.



          This is done because if the superclass initializes any private variable inside its constructor, it needs to be initialized. Having said that, it doesn't mean 2 objects are created. Only one instance of the subclass is created.



          In your case, B2 Constructor called the A1 constructor by default.



          Try doing below and you will encounter a compilation error.



          Class A1
          public A1(String msg)



          Class B2 extends A1
          public B2()







          share|improve this answer
































            0














            Constructor of a class is called when a object of that class is initialized. In your example class B2 extends class A1. When B2 object is created B2() constructor is called. Ideally you have to call super constructor in your B2 constructor like



             B2()
            super();
            System.out.println("Constructor B() called");



            So, when you B2() is invoked during object creation it will call its super class constructor. If this is not implemented by default java compiler will call superclass constructor. So your result has Constructor A() called and then Constructor B() called.
            In the below case reference is of parent class and object is of child class.
            A1 a = new B2();
            As object is B2, constructor B2() is called, which internally calls A1() by default. Now if you call a.m1() it will print 'Inside A's m1 method'. This is because reference is of parent type and parent reference can access only parent class methods. If your parent class doesn't have m1 and your class has m1, then you will get a compile time error.






            share|improve this answer



























              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













              draft saved

              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370279%2fcan-any-one-explain-how-constructors-inheritance-and-run-time-polymorphism-work%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              0














              super() is by default called from the subclass when inheriting. This is done by the compiler.



              This is done because if the superclass initializes any private variable inside its constructor, it needs to be initialized. Having said that, it doesn't mean 2 objects are created. Only one instance of the subclass is created.



              In your case, B2 Constructor called the A1 constructor by default.



              Try doing below and you will encounter a compilation error.



              Class A1
              public A1(String msg)



              Class B2 extends A1
              public B2()







              share|improve this answer





























                0














                super() is by default called from the subclass when inheriting. This is done by the compiler.



                This is done because if the superclass initializes any private variable inside its constructor, it needs to be initialized. Having said that, it doesn't mean 2 objects are created. Only one instance of the subclass is created.



                In your case, B2 Constructor called the A1 constructor by default.



                Try doing below and you will encounter a compilation error.



                Class A1
                public A1(String msg)



                Class B2 extends A1
                public B2()







                share|improve this answer



























                  0












                  0








                  0







                  super() is by default called from the subclass when inheriting. This is done by the compiler.



                  This is done because if the superclass initializes any private variable inside its constructor, it needs to be initialized. Having said that, it doesn't mean 2 objects are created. Only one instance of the subclass is created.



                  In your case, B2 Constructor called the A1 constructor by default.



                  Try doing below and you will encounter a compilation error.



                  Class A1
                  public A1(String msg)



                  Class B2 extends A1
                  public B2()







                  share|improve this answer













                  super() is by default called from the subclass when inheriting. This is done by the compiler.



                  This is done because if the superclass initializes any private variable inside its constructor, it needs to be initialized. Having said that, it doesn't mean 2 objects are created. Only one instance of the subclass is created.



                  In your case, B2 Constructor called the A1 constructor by default.



                  Try doing below and you will encounter a compilation error.



                  Class A1
                  public A1(String msg)



                  Class B2 extends A1
                  public B2()








                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 27 at 5:38









                  Somil AseejaSomil Aseeja

                  945 bronze badges




                  945 bronze badges


























                      0














                      Constructor of a class is called when a object of that class is initialized. In your example class B2 extends class A1. When B2 object is created B2() constructor is called. Ideally you have to call super constructor in your B2 constructor like



                       B2()
                      super();
                      System.out.println("Constructor B() called");



                      So, when you B2() is invoked during object creation it will call its super class constructor. If this is not implemented by default java compiler will call superclass constructor. So your result has Constructor A() called and then Constructor B() called.
                      In the below case reference is of parent class and object is of child class.
                      A1 a = new B2();
                      As object is B2, constructor B2() is called, which internally calls A1() by default. Now if you call a.m1() it will print 'Inside A's m1 method'. This is because reference is of parent type and parent reference can access only parent class methods. If your parent class doesn't have m1 and your class has m1, then you will get a compile time error.






                      share|improve this answer





























                        0














                        Constructor of a class is called when a object of that class is initialized. In your example class B2 extends class A1. When B2 object is created B2() constructor is called. Ideally you have to call super constructor in your B2 constructor like



                         B2()
                        super();
                        System.out.println("Constructor B() called");



                        So, when you B2() is invoked during object creation it will call its super class constructor. If this is not implemented by default java compiler will call superclass constructor. So your result has Constructor A() called and then Constructor B() called.
                        In the below case reference is of parent class and object is of child class.
                        A1 a = new B2();
                        As object is B2, constructor B2() is called, which internally calls A1() by default. Now if you call a.m1() it will print 'Inside A's m1 method'. This is because reference is of parent type and parent reference can access only parent class methods. If your parent class doesn't have m1 and your class has m1, then you will get a compile time error.






                        share|improve this answer



























                          0












                          0








                          0







                          Constructor of a class is called when a object of that class is initialized. In your example class B2 extends class A1. When B2 object is created B2() constructor is called. Ideally you have to call super constructor in your B2 constructor like



                           B2()
                          super();
                          System.out.println("Constructor B() called");



                          So, when you B2() is invoked during object creation it will call its super class constructor. If this is not implemented by default java compiler will call superclass constructor. So your result has Constructor A() called and then Constructor B() called.
                          In the below case reference is of parent class and object is of child class.
                          A1 a = new B2();
                          As object is B2, constructor B2() is called, which internally calls A1() by default. Now if you call a.m1() it will print 'Inside A's m1 method'. This is because reference is of parent type and parent reference can access only parent class methods. If your parent class doesn't have m1 and your class has m1, then you will get a compile time error.






                          share|improve this answer













                          Constructor of a class is called when a object of that class is initialized. In your example class B2 extends class A1. When B2 object is created B2() constructor is called. Ideally you have to call super constructor in your B2 constructor like



                           B2()
                          super();
                          System.out.println("Constructor B() called");



                          So, when you B2() is invoked during object creation it will call its super class constructor. If this is not implemented by default java compiler will call superclass constructor. So your result has Constructor A() called and then Constructor B() called.
                          In the below case reference is of parent class and object is of child class.
                          A1 a = new B2();
                          As object is B2, constructor B2() is called, which internally calls A1() by default. Now if you call a.m1() it will print 'Inside A's m1 method'. This is because reference is of parent type and parent reference can access only parent class methods. If your parent class doesn't have m1 and your class has m1, then you will get a compile time error.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 27 at 6:19









                          pro- learnerpro- learner

                          857 bronze badges




                          857 bronze badges






























                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid


                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.

                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55370279%2fcan-any-one-explain-how-constructors-inheritance-and-run-time-polymorphism-work%23new-answer', 'question_page');

                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                              Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                              Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript