JAVA How to pass initialization information to multiple superclasses - java

I have another question on constructors. I have a hierarchy of more than 2 layers, Say
A,
B extends A,
C extends B.
Can I get constructors from all three layers to fire when I create an instance of C? What if I want to pass super(int anArgumentForA, int anArgumentForB); Is that even possible? Seems like that's where it's going but I don't find a way to differentiate the arguments going to A vs B. Default constructor from B seems to run and I can't feed it the value it needs in order to run a different constructor because I don't know how.

You can have each layer call super(...) to set the information in each layer.
public Class A
{
public A(Object a, Object b)
{
//do any initialization needed
}
}
public Class B extends A
{
public B(Object a, Object b, Object c)
{
super(a, b); //This will call A(a, b)
//do any initialization needed
}
}
public Class C extends B
{
public C(Object a, Object b, Object c)
{
super(a, b, c); //This will call B(a, b, c)
//do any initialization needed
}
}
Keep in mind I don't think it is advisable to use these constructors to set the Objects to a variable at each level. So you don't want to have the constructors for A, B, and C each set some object Object x = a in the constructor. Only one, at most, level in the hierarchy should maintain a reference to the Objects being passed into the constructors.

In the world of Java, when you are extending another class, you only see your direct super class' constructor. The super class is supposed to proper encapsulate the super-super class constructor.
That means, in your case, B should provide a constructor that proper encapsulate A. In case B cannot determine the argument to pass to A's constructor, it is reasonable to ask for it in B's own constructor:
class A {
A (int aArg) {
// init base on aArg
}
}
class B extends A {
B (int aArg, int bArg) {
super(aArg);
// extra initialization base on bArg and aArg
}
}
class C extends B {
C() {
super(SOME_A_ARG, SOME_B_ARG);
}
}

As per Java Specification the constructors are not inherited by sub-classes.
So, as per you requirement you should keep in mind that the super class should have scope to pass objects.
When you are declaring a class by extending another class B extends A and C extends B , you should define the constructor
such a way so that you can customize that for initialization . This declaration always depends on the depth and hierarchy of the
inheritance .
class A{
A(Object firstObj, Object secondObj){
//Do you stuff for initialization
}
}
class B extends A{
//Keep in mind that this B class will be inherited by other class
B(Object firstObj,Object secondObj,Object thirdObj){
//Call super class constructor
super(firstObj,secondObj);
//Do other initialization stuff here
}
}
class C extends B{
//Keep in mind that this C class will be inherited by other class
C(Object firstObj,Object secondObj,Object thirdObj){
//Call super class constructor
super(firstObj, secondObj, thirdObj); //call constructor of B
//Do other initialization stuff here
}
}
It always depends how you parent class constructor has defined. It depends on the number of parameter passes to parent class constructor, you need to call accordingly from child class constructor.
Hope it will help you.

Related

Which class does "super" keyword refer to?

When working with multiple inheritance, which class does the keyword "super" refer to, the very first class created? or the parent class of the subclass we are working with?
Thank you for you consideration.
In an inheritance chain, if you call super on an instance of class D, which is derived from C, which itself is derived from B and that from A, a call to super will go to the direct parent. If the method isn't found there, the chain of parents is climbed up:
class A {
void print () { System.out.println ("from A"); }
}
class B extends A {
void print () { System.out.println ("from B"); }
}
class C extends B {
// no own print method
}
class D extends C {
void print () { super.print (); }
}
D d = new D ();
d.print ();
So here, super of D is C, where no print is found, so a lookup is made to B, as if C.print () was called. There a concrete implementation is found which is used to perform the action.
from B
This is normally not called multiple inheritance, but if you derive from multiple parents, which you can't in Java. You can implement multiple interfaces with their methods, and their names are, most of the time, not in naming conflict.
Example:
interface RocknRoller {
void roll ();
}
interface Gambler {
void roll ();
}
class Dice implements Gambler {
public void roll () { System.out.println ("roll a dice"); }
}
class Harrisson implements RocknRoller {
public void roll () { System.out.println ("while my guitar gently weeps"); }
}
class E extends D implements RocknRoller, Gambler {
RocknRoller rr = new Harrisson ();
Gambler g = new Dice ();
public void roll () {
rr.roll ();
g.roll ();
}
}
-> E e = new E ();
| Added variable e of type E with initial value E#47ef968d
-> e.roll ()
while my guitar gently weeps
roll a dice
You can have some kind of multiple inheritance via Interfaces. But interface normally don't have their own implementation of code, so when you implement multiple interfaces, you're only declaring to conform to some contract.
The implentation has to be done by yourself (or explicitly delegated). But by doing so, you're responsible yourself in solving the conflict; there is no mechanism to solve it automatically. In this example, both implementations are called in a specific order.
super() refers to the immediate parent of your class.
super() class supposed to be the first statement in constructor.
If your super class doesn't have default constructor. you have to specify the
super() call that match your parent class constructor.
refer this Link
The super keyword in java is a reference variable that is used to refer parent class objects. This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity we use super keyword. This code snippet helps to understand the said usage of super keyword.
Suppose we have 2 classes like:
class Parent {
String a ="parent string";
}
class Child extends Parent{
String a= "child string";
void show(){
System.out.println(a);
System.out.println(super.a);
}
}
public class Sample{
public static void main(String []args){
Child c= new Child();
c.show();
}
}
Now output will be :
child string
parent string
Simple a refers to child class.
super.a refers to immediate parent class.
Hope it helps. :)
Java supports linear inheritance. This can be of multiple levels but it does not support a class deriving from multiple immediate parent classes.
Now Suppose there is a below hierarchy of classes.
classes : A, B, C
hierarchy : C extends B, B extends A.
When inside any instance method (or instance block) defined in C if we use super keyword it refers to instance members and fields of immediate parent. If used in C means it refers to instance members or fields of B, if used in B it means it refers to instance members or fields of A and if used in A it means it refers to instance members or fields of Object.java
Also for invoking a particular constructor of the immediate parent class super can be used from within a constructor of child class, with the condition that it should be the first statement.
P.S. if the instance member or method is not visible to child class then compilation will fail. A class inherites all the properties and behavior from it's parent class. The keyword is useful in cases when we override the behavior in child class and still we want to invoke a behavior defined by parent class.

Inheritance in Java (default constructor)

Consider there are three classes A, B and C. Class A doesn't have a constructor, ClassB has a constructor and Class C has a parameterized constructor. something like the example given below.
public class ClassA {
}
public class ClassB extends ClassA {
public ClassB() {
System.out.println("Default cons Class B");
}
}
public class ClassC extends ClassB {
public ClassC(int a, int b) {
System.out.println("This is class C "+a+ "and"+ b );
}
public static void main(String args[]) {
ClassC c = new ClassC(2,3);
}
}
Output:
Default cons Class C
This is class C 2and3
Question 1:
To construct object C it constructs B and to construct B it constructs A first. Even though there isn't any default constructor in class A defined, the program works fine by construction its own default constructor and the B class calls super(). I don't have an issue here however when I change the Class B something like this
public class ClassB extends ClassA {
public ClassB(int a, int b) {
System.out.println("This is class C "+a+ "and"+ b );
}
}
I am getting an error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Implicit super constructor ClassB() is undefined. Must explicitly invoke another constructor
at ClassC.<init>(ClassC.java:4)
at ClassC.main(ClassC.java:10)
Why do we have to implicitly specify the super constructor ClassB(), It worked fine for the first example even though there isn't any super constructor in ClassA(). I am wondering if by default the C's constructor by default calls B's unspecified constructor just like it did for Class A.
If you specify at least one constructor in a class a default constructor is no longer created for you.
If you do not specify which parent constructor to call in your subclass the one that takes 0 parameters is used by default.
Since you added a constructor to class B that takes two integer parameters you now have to call it like this from in C as there is no longer a constructor that takes no parameters in class B:
public ClassC(int a, int b) {
super(a, b);
System.out.println("This is class C "+a+ "and"+ b );
}
Because to create an instance of C, the JVM calls the constructors of the class hierarchy.
So when you create C, you actually first call the constructor of A, then of B, then of C. Implicitly, super() is called if nothing else is specified.
If you create a constructor that takes parameters explicitly, then that overrides the default constructor
public B() {
//default constructor
}
Which means Java won't be able to invoke it for you implicitly as it does not exist, so you have to call it yourself with
public C(int a, int b) {
super(a, b);
}

Can we call a super class constructor from 2nd sub class in multilevel inheritance in java

Suppose there are three classes A, B and C. C extends B and B extends A. Can we call class A constructor directly without calling class B constructor in sub class C?
No. The constructor of a subclass will explicitly or implicitly invoke one of the constructors of its superclass to initialize itself. Constructors of other classes cannot be invoked (except to initialize different objects) whatever those classes' relationship to the class being initialized may be.
I don't think that is possible.
Anyways, if C does not relate to B, but to A, why does C extend B in the first place?
You could also try and create some protected method in A that could be called from both A's and C's constructors.
If you could try and describe what you're trying to model, maybe some alternative hierarchy would be more suitable.
No you can't, although the constructor of child class starts executing first(when you create its object) but there's always a no-arg constructor call to super in the constructor of the child(unless you manually call super with arguments) and so on. Following this hierarchy the constructor of the top most parent class although starts its execution at last, but finishes first!
Not directly .. but something like this can be done:
public class A {
A(){
....
}
}
public class B extends A {
B(){
super();
....
}
}
public class C extends B {
C(){
super();
....
}
}
// In main()
C c = new C(); // This will eventually call A's constructor

How many objects are created due to inheritance in java?

Let's say I have three classes:
class A {
A() {
// super();
System.out.println("class A");
}
}
class B extends A {
B() {
// super();
System.out.println("class B");
}
}
class C extends B {
public static void main(String args[]) {
C c = new C(); //Parent constructor will get called
}
}
When I create an instance of class C, it calls the constructor of super class. So, is there more than one object that is getting created? If only one object is created, then how is super() like another class' constructor? Does super() method internally create an object? What I know is, the constructor is also a method (I may be wrong).
My questions are:
How many number of Object is created in this case?
If one object is created then how does Super() internally call the parent class constructor?
Great question. What you are probing is how Java initializes objects - and there are a number of steps involved.
i know is constructor is also a method (Maybe i am wrong).
Nearly right. The Constructor is a special method. If you decompile a class file, you'll see the constructors get renamed to <init>. <init> is treated differently from other methods and, for example, can't be called explicitly except through use of the keyword new or super. This is so fundamental that it is implemented in the JVM itself rather than being something defined in the Java language.
How many number of Object is created in this case.
One object is created - an instance of C.
C is additionally and simultaneously an instance of B and an instance of A and also Object.
If one object is created then how internally super() is calling Parent class Constructor . How Super is able to call parent class constructor.
This is where we get into initialization - initialization is how the JVM creates a new instance of an object and sets all the member values - those of the specific class and those of the superclasses. There are several stages involved:
Load all the referenced classes and initialize those classes. Class initialization is itself non-trivial so I won't cover it here. It is well worth reading up.
Allocate a chunk of memory for holding the members of the instance, which will include the all members of A, B and C. NOTE this explains one aspect of your question: how can the constructors of the base class and its subclasses update or refer to the same object - all the members of the instance from all classes are stored one after the other in the same chunk of memory.
Initialize all the members to their default value. For example, int and float members will be set to 0 and 0.0f.
Execute or calculate the member initializers, eg:
private int a = 10;
private int b = a * 5;
private String c = Singleton.getInstance().getValue();
Note (1) that member initialization occurs strictly in the order that members are declared in the class. This means that references to members later in the declaration are broken:
private int a = b * 5; // Forward reference; won't compile
private int b = 10;
Note (2) that there is a under-used facility in Java to run arbitrary code to initialize values before the constructor is executed. These code blocks are executed at this time again strictly in order of declaration:
private int a;
private int b = 1;
{
// Initization occurs after b but before c.
// c cannot be referenced here at all
int i = SomeClass.getSomeStatic();
a = i * 2;
}
private int c = 99;
Execute the constructor of C. Constructors must either directly invoke a constructor from the superclass or the compiler will automatically add super() as the first line of the constructor. This means that the constructors are strictly executed in order:
Object
A
B
C
The object is now initialized and is ready for use. You can do some dangerous stuff if you initialize value using instance methods:
public class Wrong {
int a = getB(); // Don't do this!
int b = 10;
public int getB() {
return b;
}
}
Here, a is initialized to 0. This is because, at the point getB() is invoked, Java has cleared the value of b to the default (0), but has not yet set it to 10 in the second phase of initialization.
In summary - there is only one object and it is created and initialized in a number in stages. During those stages, the object is, by definition, not completely defined.
There will be one and only one object will be created and ie. A object.
You can imagine like when class A extends B, then all methods and variables are copied to class A.
In Code only one object will be created and super call the parent class constructor .
Prove of object creation :
package one;
public class A {
public static A super_var;
public A() {
super_var = this;
System.out.println("Constrcutor of A invoked");
}
}
package two;
public class B extends A {
public static A sub_var;
public B() {
sub_var = this;
System.out.println("Constructor of B invoked");
}
public void confirm() {
if (sub_var == A.super_var)
System.out.println("There is only one object is created");
else
System.out.println("There are more than one object created");
}
public static void main(String Args[]) {
B x = new B();
x.confirm();
}
}
This will prove that there will be only one object created.
And about Super().
What I know that it call Parent class constructor . and each constructor ahve Super() as first statement like you mention in your code . so that you know
I don't know how it internally call super class constructor .
Hope this will make you understand there is only the instace you create in program
In your case only, 1 objects is getting created.
When subclasses constructor is called, it calls the constructor of super class internally to initailize super class's members.
Invoking constructor does not mean you are creating objects. Object is already created when invoking the constructor.The objects is created by the JVM first(i.e memory is allocated on heap and then constructor is called).
Constructor are meant for initializing the members of objects.
Your classes will be internally converted to something like this
class A
{
A(){
super();
System.out.println("class A");
}
}
class B extends A{
B(){
super();
System.out.println("class B");
}
}
public class C extends B
{
public static void main(String args[])
{
C c = new C(); //Parent constructor will get call
}
}
How many number of Object is created in this case.
Only one, which is instance of C, calling super() just invokes the constructor of parent class and doesn't create object
If one object is created then how internally Super() is calling Parent
class Constructor . How Super is able to call parent class
constructor.
When you create C's instance. C's constructor gets called, which first calls B's constructor, which in turn calls A's constructor
How many number of Object is created in this case.
When you create an instance of Class C by C cInstance = new C(); a single instance(Object) of Class C is creates(None of A and B). However since C extends B and B extends A, C will have all the methods of Class A and B(Actually depends on access modifiers used but lets say for this case they are public or default).
If one object is created then how internally Super() is calling Parent class Constructor
. How Super is able to call parent class constructor.
That is how inheritance works. When a new object is created it will call it's super class constructor and that super class will call it's super class constructor and so on. In other ordinary function you have to explicitly call super(). So calling super class constructor goes bottom-up fashion while execution goes top-down fashion of the inheritance hierarchy tree
If you look at dynamics of object allocation as per this SO answer, it must be clear that using new operator, you create only one object per statement. To further clarify the doubt that there is only one object which is being created, go thru this program:
public class A {
public static int aInstanceCount=0;
public static A aInstance;
public String aInstanceVariable;
A() {
//Super();
aInstanceCount++;
aInstanceVariable="aInstanceVar";
System.out.println("class A");
aInstance=this;
}
}
class B extends A {
public static int bInstanceCount=0;
public static B bInstance;
public String bInstanceVariable;
B() {
//Super();
bInstanceCount++;
bInstanceVariable="bInstanceVar";
System.out.println("class B");
bInstance=this;
}
}
class C extends B {
public static void main(String args[]) {
int instanceCount=0;
C c = new C(); //Parent constructor will get call
if(A.aInstance!=null){
instanceCount++;
System.out.println("Value of aInstanceVariable: "+A.aInstance.aInstanceVariable);
}
if(B.bInstance!=null){
instanceCount++;
System.out.println("Value of bInstanceVariable: "+B.bInstance.bInstanceVariable);
}
A a=A.aInstance;
B b=B.bInstance;
System.out.println("bInstanceVariable of B earlier: " + B.bInstance.bInstanceVariable);
//Now we are changing the bInstanceVariable of c which is inherited from B
c.bInstanceVariable="bInstance After modified by C";
System.out.println("bInstanceVariable of B after: " + B.bInstance.bInstanceVariable);
System.out.println("aInstanceVariable of A earlier: " + A.aInstance.aInstanceVariable);
//Now we are changing the aInstanceVariable of c which is inherited from A
c.aInstanceVariable="aInstance After modified by C";
System.out.println("bInstanceVariable of A after: " + A.aInstance.aInstanceVariable);
}
}
The output:
class A
class B
Value of aInstanceVariable: aInstanceVar
Value of bInstanceVariable: bInstanceVar
bInstanceVariable of B earlier: bInstanceVar
bInstanceVariable of B after: bInstance After modified by C
aInstanceVariable of A earlier: aInstanceVar
bInstanceVariable of A after: aInstance After modified by C
If you can notice, the super constructor is implicitly getting called each time if a subclass object is created, but since the new operator is used only once, there is only one object which is actually allocated the space. And by modifying the aInstanceVariable via C object c, we are actually changing the aInstanceVariable of aInstance. So it clearly proves that there is actually one object.
Steps of object creation when you call a constructor to create object:
Memory allocation using init is done. This init makes a system call to allocate memory for object creation.
Then your constructor is called to initialize the object's fields.
Then it calls super class constructor (If there's any super class) and Step 1 through 3 repeats.
What you see when you decompile a class file using javap shows different calls to be made. init makes system call to initialize memory allocation but object's field are initialized when constructor's code is run.
I am not sure how polymorphism/overriding works at the time of GC.
But it should be worth a try to override finalize method in all your classes and check when JVM exits main method.
If only C object is created, it should call finalize for 'C'.
If all A,B, C object is created, it should call finalize for A,B, C.
I think this is simplest check you can apply.
class A {
A() {
//Super();
System.out.println("class A");
}
public void finalize(){
System.out.println("Class A object destroyed");
}
}
class B extends A {
B() {
//Super();
System.out.println("class B");
}
public void finalize(){
System.out.println("Class B object destroyed");
}
}
class C extends B {
public static void main(String args[]) {
C c = new C(); //Parent constructor will get call
}
public void finalize(){
System.out.println("Class C object destroyed");
}
}
I agree with the previously posted answers, but want to add a reference to the ultimate authority on this issue, the Java Language Specification.
The expression new C() is a "Class Instance Creation Expression". Section 15.9.4 Run-time Evaluation of Class Instance Creation Expressions describes the run time steps involved in creating an object. Note that it refers to "the object", and only allocates space once, but states "Next, the selected constructor of the specified class type is invoked. This results in invoking at least one constructor for each superclass of the class type."
This all becomes much clearer by distinguishing between creating a new object, and invoking a constructor. Invoking a constructor only does part of object creation, the part that runs initializers, superclass constructors, and the body of the constructor. Because a C is also a B, the B constructor has to run during creation of a C.
The super keyword enables a subclass to call the methods and fields of its superclass. It is not an instance of the superclass object but a way to tell the compiler which methods or fields to reference. The effect is the same as if the subclass is calling one of its own methods.
Examples:
Consider a subclass Employee that extends its superclass Person:
public class Employee extends Person{
public Employee()
{
//reference the superclass constructor
super();
}
public String getName()
{
//reference superclass behaviors
return super.getFirstName() + " " + super.getLastName();
}
}
The super keyword can be used to reference the constructer of the Person class or any of the behaviors or fields that it has access to (e.g., getFirstName() and getLastName()).
In your Case One object is created
while doing the following, this super() will provided by Compiler Implicitly
class A {
A() {
System.out.println("class A");
}
}
class B extends A {
B() {
System.out.println("class B");
}
}
class C extends B {
public static void main(String args[]) {
C c = new C(); //
}
}
It is similar to calling a super() inside your methods
B() {
super();
System.out.println("class B");
}
The super keyword can also be used when a method is overridden in the current class, but you want to invoke the super class method.
super() will makes the all constructors reference to one class. (For easy understanding: Its like all the member functions are comes under a same class.)
Its going to call all the constructor methods only.
So its done the work of calling constructor only, so super() will not done any object creation. Its just referring the member functions.
If you add one more line of Code System.out.println(this.hashCode()) will remove your confusion.
Here in All Case hashCode() will print same hashCode all the time. It means there is one and only one unique Object is Created.
class A {
A() {
// super();
System.out.println(this.hashCode()); // it will print 2430287
System.out.println("class A");
}
}
class B extends A {
B() {
// super();
System.out.println(this.hashCode()); // it will print 2430287
System.out.println("class B");
}
}
class C extends B {
public static void main(String args[]) {
C c = new C(); //Parent constructor will get called
System.out.println(this.hashCode()); // it will print 2430287
}
}
but there is two Constructor is getting invoked to initialize the Parent member variable. I think if you know the concept of super() keyword which invokes the Constructor of parent Class and Initialize the member Variable of parent Class.
3 constructors will call
Code:
class A
{
A()
{
System.out.println("In A");
}
}
class B extends A
{
B()
{
System.out.println("In B");
}
}
class C extends B
{
C()
{
System.out.println("In C");
}
}
public class InheritanceTest {
public static void main(String args[])
{
C c1=new C();
}
}
Output:
In A
In B
In C

using constructor from the super class

Java does not allow multiple inheritance, meaning that a class cannot inherit from two classes, which does not have anything in common, meaning that they are not on the same inheritance path. However, a class can inherit from more classes, if these classes are super classes of the direct super class of the class. But the class inherits from these classes indirectly, meaning that it does not "see" anything from these upper super classes, right? I was confused when considering constructors (using super() in the constructor). For example, if we have the following classes:
public class A {
public A() {
....
}
}
public class B extends A {
public B() {
super();
....
}
}
public class C extends B {
public C() {
super();
....
}
}
the constructor of class C invokes first the constructor of class B using super(). When this happens, the constructor of B itself invokes first the constructor of A (with super()), but the constructor of C does not know anything about the constructor of A, right? I mean, the inheritance is only from the direct super class - the first (nearest) class from the inheritance hierarchy. This is my question - with super() we mean only the constructor of the direct super class, no matter how many other classes we have in the inheritance hierarchy.
And this does not apply only for constructors, but for any methods and instance variables..
Regards
You have to invoke some constructor in your immediate base class. This can be
public class A {
public A() {
....
}
public A(String foo) {
....
}
}
public class B extends A {
public B() {
super();
.. or ..
super("ThisIsAB")
}
}
public class C extends B {
public C() {
super();
....
}
}
So for constructors you cannot AVOID constructing your intermediate base classes, but you can choose which constructor to use. If there is only the no-args constructor it's all handled for you with an implicit call to super. With multiple constructors you have some more choices.
super can refer to any non-private variable or method in any base class. So methods and variables are not the same as constructors in this respect.
Even if you could avoid calling the intermediate ctor, you wouldn't want to, because that would mean you had uninitialized pieces of the intermediate classes that might be acessed by the bottom-most derived class. To horrible effects.
But I sense that you're trying to trick your way around Java to do multiple inheritance. That is a Bad Thing. Instead, you can do it Java-wise by using an interface
class B extends A implements C {
// ... implement C methods here
}
or by using aggregation
class B extends A {
private C c;
}
Constructors for all parents are called. In fact, deep down C knows about A because B extends A. For example, if the class A contained method foo(), then you could call foo() from C.
So from your example, C calls the constructor from B, which calls the constructor from A. Additionnally, A also extends from the class Object. So the constructor in the class Object is also called!
Furthermore, you do not need to add a call to super(). If there is no call for the constructor of the parent, super is call implicitly.
As you say, C's constructor invokes B's constructor which invokes A's constructor. You can call any "A" methods on a C object, and a C object can see non-private fields in A.
Even if you override A's method "foo" in C, you can get the A version with "super.foo()", assuming B doesn't also override it.
As far as C knows, anything that it does not overwritten in C is contained in B, even if under the covers class A is where the implementation might be.
public class A {
public A() {
}
public void aMethod() {
}
}
public class B extends A {
public B() {
super();
}
}
public class C extends B {
public C() {
super();
}
public void doWork() {
super.aMethod();
}
}
So in this case A handles the implementation of aMethod(), even though calling super() in C's constructor called B's constructor directly, not A's.

Categories

Resources