Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly? -


I have a question about succession in java.

I have two classes, A and b , and class B, inherits A from:

< Pre> public class A {public A () {System.out. Println ("hi!"); }} Extension of Public Square B A {public B () {System.out.println ("Bye!"); } Public static zero main (string [] args) {bb = new b (); }}

When I run Program B, the output is:

  Hi! Bye!  

Question : Why < Constructor of Code A applies when I create it The purpose of class B ?

I know that everything from B has inherited - all the examples or class variables, and all the methods, and in this sense B in one object, some characteristics of A and B. There are some other characteristics defined. However, I did not know and I did not imagine that when I make the B's object, the constructor of A will also be brought. Therefore, write it:

  bb = new b ();  

Creates Two Objects - One Type B, and One Type .

It is interesting,

Can anyone explain why this happens?

This two objects are not created, only one: b .

When you get from another category, you should call super () in your constructor. If you do not do this, then the compiler will include the call for you as you can clearly see.

Superclass constructor is called because otherwise the object will drop in an irregular position, potentially unknown sub-squares for the developer.

After adding the compiler super call, your subclass actually looks like this:

  expanding public square b A {public B () {super (); Println ("Bye!"); }}  

Comments