Java constructors and super() - java

I have seen a few questions on the topic, but they all assume knowledge of inheritance. The example in my book is before the inheritance chapter, so the parent class is java.long.Object.
1. Scenario: my class FotoApparat has no custom constructor or any constructor at all and I create an instance of FotoApparat with FotoApparat meinFotoApparat = new FotoApparat()
Question: As my class has no constructor and also no super() call, I assume the program checks the parent Object class for a suitable constructor, which should be new Object(), right? If yes, is this still considered an "implicit" super() call?
2. Scenario: I create a custom constructor (by using eclipse source) which takes on parameters. In the generated constructor the super() call is added in the very beginning, which I assume is the actual implicit call I keep reading about. I read on javapoint that when an instance of a class is created, an instance of the parent class is also created, which is referenced by super().
Question: I read that this super() call can be removed from the constructor, but if it is removed and I use a constructor that takes on parameters, then (without super()) how is this parent object created ?!

Scenario 1:
If you don't define any constructor, a default, no-argument, constructor is created for you. That's the one that is called when using new FotoApparat(). This default constructor then calls the constructor on Object (see scenario 2.)
Scenario 2:
If you don't explicitly call super(), this call is still done implicitly. It is possible however that the parent object does not have a constructor without arguments, in which case you are required to call a specific constructor.

As my class has no constructor and also no space() call, I assume the program checks the parent Object class for a suitable constructor
Not quite. If you don't define a constructor, the compiler creates one for you. This constructor takes no arguments, and the only thing it does is call the super class constructor super().
when an instance of a class is created, an instance of the parent class is also created
Not quite: only one instance is created. There is no separate parent class instance.
The statement is not entirely incorrect because thanks to inheritance, the one instance of the child class that is created is also an instance of the parent class.
I read that this super() call can be removed from the constructor, but if it is removed and I use a constructor that takes on parameters, then (without super()) how is this parent object created ?!
In this scenario the compiler inserts a call to the no-argument super class constructor super(). But this does not create a separate "parent object" - only one object is created.
What your studies may not have made clear is the distinction between object creation and initialization. Calling a constructor does not "create" an object. An object is created by reserving space for it in memory. After the memory has been reserved, the constructor is called to "initialize" the object.

Related

How does the parent class's defined method get called in a sub-class object?

This is a bit more of an implementation-related question, or I could be overthinking it. Let's say I have a subclass that inherits from the parent class. From my understanding, it will inherit the method definitions from the parent class but not the constructor. We need to provide or the compiler will provide constructor through the super method call. The reason we do this is that the method definitions we obtain from the parent class in the sub class will not exist without a parent class object instance.
Does this mean, when I call a parent class object defined method that is not overridden yet in the subclass, will be internally called inside the subclass on a parent object instance? I was thinking that would be the case since the sub-class does call the parent class constructor and make an instance of it.
I think you have been mislead by the term "constructor". If the wording had been "initializer", IMHO that would have been clearer - but the established term is "constructor".
If your subclass Sub extends a parent class Parent, then creating a Sub instance will not create a second, separate Parent instance.
When your Sub constructor calls the super() constructor, this just means that the aspects described in the Parent class get initialized the way that Parent constructor wants it, e.g. filling the fields defined in Parent with appropriate values. This super() constructor call does not construct/create a new instance, but initializes the Parent-defined part of the one and only instance, and that's why I think the name "constructor" misleading.
After that super() call, your Sub constructor is free to do its turn. All this happens on a single instance that combines fields (and methods) from both classes.
So, when you call a Parent-defined method on a Sub instance, there is no distinct Parent instance that might receive the call, it all happens on the single Sub instance. As the method is defined inside Parent, it does not know anything about the Sub extensions to Parent, and e.g. can't access fields defined in Sub (unless using "dirty tricks" like reflection).
If you like, you can think of a Sub instance as being a Parent instance where some fields and methods have been added to the end. Parent-defined methods work on the Parent part of the instance(1), and Sub methods see the complete instance.
The reason we do this is that the method definitions we obtain from
the parent class in the sub class will not exist without a parent
class object instance.
So, this is not true. The "parent class object instance" does not exist (at least not in the sense of an instance distinct from the subclass one), it is the first part of the subclass instance, which is then followed by the subclass fields.
(1) There are a few caveats, e.g. if a Parent method is overridden in the Sub class, but IMHO that goes beyond the scope of this question.

What does the default constructor in the class OBJECT do? [duplicate]

This question already has answers here:
Why call super() in a constructor?
(8 answers)
Closed 5 years ago.
I'm a Java beginner learning about Java compiler rules as below:
If the class has no super class, extend it to Object class
If the class has no constructor, add a default no-parameter constructor
If the first line of the constructor is not "super()" or "this()", add "super()" to call the default constructor of the super class.
I understand that all objects we create are derived from the super class Object.
My question is what does the constructor in the Object class do when called?
Edit: My question is about what the constructor does in the class Object? I'm aware that subclasses call superclass's constructor by default.
For example, I have the following code (where I explicitly extend to Object and call super() to illustrate what the compiler does). My question is, what does the call to super() do?
public class Person extends Object
{
private String name;
public Person(String n)
{
super();
this.name = n;
}
}
My question is, what does the call to super() do?
It calls the default constructor for java.lang.Object. And to answer what you seem to be really asking, from the Java Language Specification, #8.8.9
8.8.9. Default Constructor
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
The default constructor has the same accessibility as the class (§6.6).
The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
The default constructor has no throws clauses.
If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
Note the final paragraph.
All Java classes that don't have any explicit superclass, extend from Object, except for Object itself. There's no need to make it explicit in your code, the compiler will take care of.
Also, the super() call in the constructor will invoke the constructor of Object. If you look at the implementation, you'll see that Object doesn't have any constructor at all, so it'll use an implicit empty constructor which does nothing. Details such as constructing a vtable to make sure that the inherited methods are there to use or initialising the object's monitor are not part of the constructor but are performed by the JVM implementation when the new operator is called.
public Object() {
}
The Object class has few methods that come handy in most of the classes. For example, the infamous toString() is implemented in the Object class. Also, the hashCode() is implemented there.
I'd recommend you to have a deep look at the Object.class file to understand what methods are inherited in every single Java class.
Regarding your 3 rules at the top, are "good" for academic purposes but never used in reality. You'll never see an explicit extends Object, and only call the super() or this() when you need to overwrite the default behaviour.
Also, avoid abusing of inheritance and use more composition (implement an interface), although, it depends on the every use case.
For example, I have the following code (where I explicitly extend to
Object and call super()). My question is, what does the call do
super() do?
Actually, Object() does nothing.
Now you should not reduce the constraint to invoke super() (with args or not) for any subclass constructor to the case where you have a class that doesn't extend a class explicitly.
This case is the only one where invoking super() may seem not really useful.
But as soon a class extends a class distinct from Object, this constraint makes really sense as the child construction has to apply first its parent construction.
But the language specifies this point in a general way. It has no exception for classes that extend directly Object.
Probably because, it makes things more simple and that is not a real constraint as the compiler adds for you the call to the super default constructor : super().

object creation in java behind scenes (java object instantiation)

I understand that there are three parts to object creation:
Declaration
Instantiation
Initialization
classA{}
classB extends classA{}
classA obj = new classB(1,1);
Instantiation
It has to create an object using new operator
and this object must have all the fields related to classB (initialized to default values does this step give a call to default constructor?) this is instantiation
does it mean this step is initialization using java's default constructor?
Initialization
this object is then passed down the hierarchy giving calls to various constructor in the way to get initialized (which comes under initialization)
and the final obj is created by 'classB(1,1)` constructor whith required Initializations
but how is the object mentioned in instantiation step being created initially with all available fields?
please point out if anything i said is wrong
If the class has no constructor a default constructor is implicitly defined.
Constructors have method name <init> in a stacktrace.
A constructor call does the following:
the object is created, with all fields nulled: 0, 0.0, null, ...
the super constructor is called, possibly implicit if not present in the code.
all initialized fields (A a = ...;) are initialized by doing the assignments.
the rest of the constructor is executed.
Roughly, the way it works is:
The new bytecode instruction is executed with a symbolic reference to the class of the object to be created. As described in the Java Virtual Machine Specification, this allocates a new object in the garbage collected heap and initializes all fields to their default values.
One of the object's constructors is called. (Which one is called depends on what was coded.) All constructors (except for Object itself) must, as their first step, call another constructor in the same class or call a constructor in the superclass. (If you don't code one of these calls in a constructor, the compiler automatically inserts a call to super();—the default superclass constructor—at the start of that constructor. Each constructor in the chain—starting with Object at the deepest level of constructor calls—does whatever setting of instance fields in the object.
The second step might be modified slightly if there are instance initializers in the class declaration. See Chapter 8 of the Java Language Specification for details.

super() method not giving error when no parent class is defined

class child
{
child()
{
super();
System.out.println("Hello");
}
public static void main(String arg[])
{
child obj=new child();
}
}
In this code when I a create an object of class child , the child constructor is called. But why is it not giving error as there is no parent class. What does the super() do here?
Whose constructor is the super() keyword calling?
In Java every object implicitly extends Object. Calling super here will just call Object's constructor. On another note you should really abide by naming conventions such as capitalizing class names.
It is calling the constructor of the Object class as all object in java extends by default to the Object class.
From documentation:
Class Object is the root of the class hierarchy. Every class has Object as a superclass.
All objects, including arrays, implement the methods of this class.
You're invoking the Object method, from which all other classes descend eventually.
First up, clarifying the class hierarchy in this situation, the inheritance section in the Java tutorial states:
Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.
Then, for the tutorial stuff on using super:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.
Every class we create in Java is an implicit descendant of "Object" object (in other words, subclass of Object). Hence when ever you are making a call to super() it implicitly calls the constructor of Object class. The basic reason to have this feature is to generalize the common features like:
synchnronizaton - like wati()
object identity - like hashcode(), equals()
and many more.
Thanks,
JK
The Object class, in the java.lang package, sits at the top of the class hierarchy tree. Every class is a descendant, direct or indirect, of the Object class.
All objects, including arrays, implement the methods of this class. Thats why super() in your case is actually calling the constructor of Object class.

What is Implicit constructors on Java

Is it mandatory to call base class constructor in Java?
In C++ it was optional, so I am asking this.
When I extend ArrayAdapter, I get this error: "Implicit super constructor ArrayAdapter<String>() is undefined. Must explicitly invoke another constructor"
So, what is the purpose of calling base constructor? When I create object base class constructor will call & then it comes to derived right.
The no-args constructor is called implicitly if you don't call one yourself, which is invalid if that constructor doesn't exist. The reason it is required to call a super constructor is that the superclass usually has some state it expects to be in after being constructed, which may include private variables that can't be set in a sub-class. If you don't call the constructor, it would leave the object in a probably invalid state, which can cause all kinds of problems.
It's not necessary to call the no-args constructor of super class. If you want to call a constructor with args, user super keyword like show below:
super(arg1, ...);

Categories

Resources