Does a superclass instance also being created when creating a subclass instance? - java

I have seen many threads (e.g.: Inheritance in Java - creating an object of the subclass invokes also the constructor of the superclass. Why exactly?) saying that the instance of superclass will NOT be created when creating a subclass instance. I actually agree with this opinion.
However, I can't find any official materials (from Oracle) to back this up. I searched a couple of hours and cannot find anything. Can anyone refer me to a reliable resource to confirm this?

When you create a new instance and the class constructor is called, enough memory is being reserved in the heap for that instance's attributes to be stored. Those attributes comprise both:
Attributes directly belonging to your class definition;
Attributes belonging to all upper nodes in your class hierarchy tree.
Yes, the superclass constructor is called, but with the sole purpose to initialize attributes of the superclass. It never means a new object of the superclass will be created.
Check these links, they may help you to understand the process:
http://www.javaworld.com/article/2076204/core-java/understanding-constructors.html
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
On the second link, documentation states: It is new which creates the object. That is: It reserves memory for all the class references (Object attributes) and primitive values.
Then, the constructor is called, and its aim is to initialize enclosing class' attributes.
Since the object attributes are references in Java, the constructor may use new to create object attributes, their references will be the values stored in your object's memory.
The superclass constructor just continues this task for your class inherited attributes.

When an instance of a derived class is created the heap allocation will be something like (*):
Standard JVM object header (with pointer to Class object for DerivedClass)
Instance fields for class Object
Instance fields for class BaseClass
Instance fields for class DerivedClass
So in effect, if you ignore the DerivedClass instance fields the object looks remarkably like an instance of BaseClass, and the JVM can reference the object as if it were an instance of BaseClass and have no difficulty doing so.
Similarly, in the Class object for DerivedClass is a "virtual method table" with:
Virtual method pointers for Object
Virtual method pointers for BaseClass
Virtual method pointers for DerivedClass
The JVM makes virtual calls by indexing into this table to find a specific method, knowing that, say, hashValue is method number 5 and printTheGroceryList is method number 23. The number needed to call a method is determined when a class is loaded and cached in the method reference data in calling classes, so calling a method is: Get the number, go the the Class object pointed to by the instance header, index into the virtual method table, pull out the pointer, and branch to the method.
But when you look closely you will see, eg, that the pointer in the Object group that points to the hashValue method actually points to the one in BaseClass (if BaseClass overrides hashValue). So the JVM can treat the object as if it were an Object, invoke hashValue, and seamlessly get the method in BaseClass (or DerivedClass, if it also overrides the method).
(*) In practice the instance fields may be intermingled to a degree, since "aligning" fields from a superclass may leave gaps in the heap allocation that fields from a subclass can fill. This is simply a trick to minimize object size.

Base Class's object is not instantiated when a Derived Class's object is instantiated. Inheritance only brings certain attributes and methods of Base Class to Derived Class. Constructors/destructor of base class are called along with those of derived class when object of derived class is made/destroyed. But this does not mean object of base class is also made.

An object is identified by its address, stored in variables of object types. the new operator returns that address, and only one address, so there can only be one object. You can check this by looking at System.identityHashCode(this) in sub- and superclass constructor, for example.

Related

It's about subclass and superclass

I would like to ask some concepts:
The object of the subclass belongs to the parent superclass.
Does the method of the parent class exist in the memory of the subclass? that is, copy the attributes and methods of the parent class to the subclass?or
How do subclass objects manipulate the attributes and methods of the parent class?
thx.
The object of the subclass belongs to the parent superclass.
"Belongs to" is poor terminology. A better way to say this is that an object that is an instance of a class C is also an instance of C's immediate superclass. (In fact, it is an instance of all of the superclasses of C.)
Does the method of the parent class exist in the memory of the subclass?
You have a fundamental misconception here. Methods do no exist in the memory of a class. Or the memory of an instance.
They are actually held in memory separate to both classes and instance.
The closest that anything comes to what you are saying is that a class descriptor will include internal references to methods. But that is all hidden from view, and the details should not concern you.
By contrast, the (non-static) attributes of an object (defined by the class) are actually part of the object. And indeed the attributes defined by the subclasses and all superclasses are all part of the same object.
Think of it this way:
An Animal has legs.
A Cat is an Animal.
A Dog is an Animal.
A Cat has whiskers.
The legs of a fido the Dog are part of fido.
The legs of a fluffy the Cat are part of fluffy.
The whiskers of fluffy the Cat are part of fluffy.
How do subclass objects manipulate the attributes and methods of the parent class?
Objects don't "manipulate" methods. They call them. How they call them is implementation dependent, but conceptually they find them in the class descriptor.
A method access attributes by looking at the object via its reference. Since the subclass and superclass attributes all belong to the same object (see above!!), they are accessed the same way.
It just literally extends it. It's like you would take superclass body and add code of subclass to it to create new class.
There are some minor differences like ability to have 2 versions of the same method in subclass like methodA() and super.methodA() or that instance of Subclass can be treated as Subclass and Superclass (polymorphism).
But in general you can think of it in such way of subclass having all properties and definitions of subclass.

Java Constructors and initializing class variables

In Java, does the constructor of a class create an instance of that class? And if it does, does it also initialize the variables of that class?
Constructor doesn’t create the instance of the Class.
Instance creation is done using either:
1.Using Class.forName()
2.ClassLoader loadClass()
3.Using clone()
4.Deserialization
5.Using reflection
6.new keyword
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1.Constructor name must be same as its class name
2.Constructor must have no explicit return type
Types of java constructors
There are two types of constructors:
1.Default constructor (no-arg constructor)
2.Parameterized constructor
Constructors don't create objects. They merely initialize objects(and their data members) once they are created using parameters(when provided) or to default values.
When you create an instance of the class using new operator, the constructor of the class is called so as to initialize the instance variables.
If the constructor defined is default, then instance variables have to be assigned to the newly created object explicitly.
However when you override a constructor using fields, then the instance variables for that newly created object are assigned during object creation.
I would love to explain this in a very simple language. In the real-world to build something, we need two things first is its prototype/model, and the second is someone who can create it based on that prototype.
A very relevant simple example is to build a house, you first need its blueprint(map), then a constructor who can build it based on that blueprint. So, similarly in the programming language
Object: A real-world entity for which we create a class.
Class: A class describes the "blueprint" of the objects that are made out of it (are instances of it).
For software development, we first have to think about the objects(any real-world entity), then we create a class (blueprint) for it, which contains its attributes.
After creating a class when we need to create one or more objects based on it, for this, we need a constructor to build it.
Whenever we create a new object, we have to use new keyword, and it tells the constructor to create the object.
When you are initialing variables in a class they are just part of the blueprint, based on that, the object will be created. So, without a constructor, you cannot create new objects, but there are some exceptional cases and tricks where you can create them without calling constructors.

Overriding with Superclass Reference for Subclass Object

I have recently been moving through a couple of books in order to teach myself Java and have, fortunately, mostly due to luck, encountered very few difficulties. That has just changed.
I read a section on the following under inheritance and the whole superclass subclass setup
-- When a new superclass object is created, it is, like all objects, assigned a reference (superReference in this example)
-- If a new subclass object (with the defining subclass extending the superclass) is created, and then the superReference reference is set to refer to that instead of the original object, it is my understanding that, since the reference is made for a superclass, only members defined by the superclass may be accessed from the subclass.
First - is this correct?
Second: If I am overriding a method and therefore have one in the super and one in the sub, and I create a superclass object and then assign its reference, as I did above, to a subclass object, by the principle called something like Dynamic Method Dispatch, a called overridden method should default to accessing the subclass method right?
Well, my question is:
If a reference to a superclass-object is retooled for a subclass-object and will deny direct object.member access to subclass-defined members, only supporting superclass-defined members, how can, if a superclass reference is retooled for a subclass object, an overridden method apply to the subclass-object if access is limited by the superclass-originated-reference-
If you try like:
class SuperClass{
int intVar = 0;
void method(){
//in super class
}
}
class SubClass extends SuperClass{
int intVar = 2;
void method(){
//in sub class
}
}
Then
SuperClass obj = new SubClass();
int val = obj.intVar;// this is taken from SuperClass as variables are decided on reference basis
//if both superclass and subclass contain the same variable it is called shadowing
obj.method();// it is taken from the SubClass as it is method overriding
//and is decided at runtime based on the object not the reference
Check comments. Hope this helps.
only members defined by the superclass may be accessed from the subclass.
First : This is just plain wrong. The subclass may access it's own member without a problem. However once you have assigned a subclass instance to a super class variable (reference) the you can only call methods or members made accessible from the super class only. Is this what you meant to say?
Second : Methods that will be executed are the methods in the instance (object). Not the methods in reference (variable) type. So yes overridden methods will always be executed.
Third : A subclass may override a method but not a instance property. Whatever member variables are in the super class will be in the subclass as well. And you can override methods in the subclass just so long as you keep their existing access modifier or use a more accessible access modifier.
In Oracle documentation doesn't mention that or at least it is not clear or explicitly explained. This behaviour seems to me like virtual methods in C++ with the difference that in such language it is clear through the use of the keyword virtual preceding the methods defined in the base or parent class (superclass in java) and that must be redefined in the child class. In C++ there are not virtual variables, just virtual methods.
In that case, when we have a pointer (reference) to a base class that points to an instance of a child class and there are methods with the same signature and variables with the same name in both the parent and child classes, the definitions of the methods that will be executed are those of the parent class if they are not preceded by the keyword virtual, on the other hand the definitions in the child class will be executed for the methods declared as virtual.
In the case of the variables, the ones in the base class are taken and not the ones in the child classes.
Resuming, the similarities are:
-In java, variables are taken based in the reference
-In C++ there are not virtual variables
So in the case we are talking about, hidding variables in the child classes or subclasses are not taken but the hidden
-In java, methods are taken based on the object or instance
-In C++ virtual methods must be redefined in the child classes and those are taken

What is constructor in java, if it is not a member of class?

What do we we call a constructor, if it is not a member of a class as stated in Oracle doc: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I think the term "member" was defined to exclude constructors for the sake of convenience. Constructors, even public ones, are not inherited; members are inherited (unless they are static and/or private). It would be awkward when talking about the rules of inheritance to always have to say "members except constructors".
From the Java Language Specification, §8.2:
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
Just call constructors "constructors".
Its a special method that every class has, which is called after creation of the object. in JVM its called using invokespecial so, lets just call it a special method?
And since there is just 1 special method in Java - they all call it "constructor"
All the doc is saying is that the constructor is not inherited by default. Since the constructor is a method that is invoked on the construction of the object in the memory heap, then once you create a subclass that inherits from a super class, the constructor of the super class is not invoked by default.
For instance if you have a class Vehicle and a subclass Car, assume the Vehicle constructor is as follows:
public Vehicle(String vehName) {
this.vehName = vehName;
}
Then, even though your class Car inherits from class Vehicle, the vehName member (field) will not be set as the constructor above does.
So you will need to do something like this:
public Car(String vehName) {
super(vehName);
}
Hope that helps
In Java, a class body (the area between braces) can contain the following key items: (1) Fields (2) Methods (3) Other Classes (nested classes) (4) Constructors (5) Initializers
An object created from a particular class shall take the shape that is similar to the blueprint (class) from which it's created. Now, if you look at items that can be contained in a class body, only item (1) to (3) help in determining what sort of object can be created from a particular class definition.
Constructors and initializers only play part in actual creation of the object (e.g. initialization of already defined fields), but do not determine what shape/state that object shall carry, and what behaviors it will display.
For this reason, to me, it make sense to call item (1) to (3) class members (i.e. class members are those items within a class body that determine how an object created from the class looks like and behave); whereas constructors and initializers are not members because their absence in a class definition does not affect a class state and behavior.
As such, only class members can be inherited as the whole point behind inheritance is to enable a subclass reuse state and behavior of its superclass.
A Constructor is a method which is in a class which is used to create a new instance of that class.
Being a member of a class just means that the item in question is in the class.
Constructor is a method which name is same as the class. It is used to initialize the object of class. It's implicit in action. Parametric constructor initialize object with different value.

Instance Vs Object

When we have base and sub class in java, and we instantiate the sub class, we get one instance or two instances? If we get two objects, how many instances we get? Does one instance holds the two objects of base and sub class or two separate instances?
If you instantiate a subclass, you will get just one object/instance. This single instance will contain all of the fields of the subclass (which includes the fields defined by its parent classes).
Remember that subclasses means that you're defining a new class which derives from an existing parent, that is it inherits those definitions. So if the parent declares a field called id, the subclass will also have a field called id, and so an instantiation of that subclass will contain an id field. This field is declared in the parent class, but it does belong to the subclass.
If you instantiate the subclass, there is no instantiation of the parent. No object exists whose runtime class is the parent class.
(I'm not sure what your distinction is between "object" and "instance" in your question. You've used them in a way that implies they are different, but typically they mean exactly the same thing. An object is an instance of a particular class.)
You get a single instance that is of the two classes - the base and the subclass.
Try to understand it with this example: there is a class Mammal and the class Human. You belong to both of them - nevertheless, there is a single instance of yourself. If there were two persons in the room, you would have two instances of both classes!
Instance == object ... both are the same, just 2 different names. If you create one object (maybe a subclass) you get one object.
When we have base and sub class in java, and we instantiate the sub
class, we get one instance or two instances?
We get one instance because each Java class instance is contained in a single object.
If we get two objects, how many instances we get?
The term "instance" is synonymous to object. Saying one instance is just a different way of saying one object.
Does one instance holds the two objects of base and sub class or two
separate instances?
No. Java compiler creates class bytecode that contains the functionality of both base and extension, so instantiating that class results in a single object.
What is then the logical difference between instance and object?
In the context that you are using these words, there is no difference. An instance (of a class) is an object, and vice-versa.
However, in the broader context, an instance (of a type) is not necessarily an object - it depends on the type. For instance that you could say that 42 is an "instance" of the int type.
new classA(); //Here you create an instance of a class
classA ob //create object named "ob" and datatype "classA"
And now we assign the instance to the object
classA ob = new classA();
like
int num = 10

Categories