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
Related
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.
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.
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.
Is a class an instance of an object?
Can you create many objects from the same class, and can a class have many instances?
Thank you for your help, I'm reading a book on Java programming and am currently confused about these definitions.
A "class" conceptually is not an object (or an "instance of an object", which makes no sense really), but rather a sort of blueprint from which objects are created. Objects are instances of classes. You can indeed instantiate a class many times.
Don't confuse this with instances of the Class class, which are objects (e.g. String.class, int.class etc.).
A class describes the structure of an object and is not an instance.
An instance is an object that conforms to the structure defined by the class.
There can be many instances of a class.
For example, consider a "Person" class. When creating the class, you could say, "A person may have a first name or a last name," but you're not creating an actual person, you're just saying what makes up a person. When you create a person, you create an instance of the class "Person" and you may have many people, which means having many instances of the class "Person".
The CLASS works as a BLUEPRINT which allows you to create OBJECTS based on this BLUEPRINT.
You CAN create many instances (OBJECTS) of the same CLASS.
To clarify:
Object - Objects have states and behaviors. Example: A dog has states
- color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blue print that describes
the behaviors/states that object of its type support.
A class is not an instance of an object. In fact, an object is an instance of a class. Here is the explanation,
Conceptually, each class represents and describes the characteristics of an independent concept in a program. these characteristics are also owned by any object of this class type. Usually, instance variables of a class defines properties of an entity. For example, if you have a class called Student, then obviously this class should have instance variables that represents student's characteristics such as name, level, grade...etc. Also, it can have methods like getGrade (), getName (). Now, any object of type Student will have the properties defined by its class (eg. name, level..), meaning the information stated in the class is encapsulated in its objects. Also, this object can be used to reach for the methods like getGrade or getName (again because these methods are encapsulated inside each object).
The class is the definition of a single concept structure, and the object is an implementation of this structure. That's why, we say, an object is an instance of a class. Note that we can have various instances (objects) of a single class, each object will encapsulate the same structure defined by its class, but with different values. For example, you may have several objects of the class Student each represents a different student with different name, level, grade...etc. Although these objects are different, they share the same structure, meaning they are all students.
Data encapsulation provided by class/object technique is really useful. Suppose you have 100 students who you need to store their names, levels, and any other related information. Instead of defining 100 String variables to store each student name, and 100 int variables to store the levels, you simply create a class which defines a student structure and create as many objects as you want. It saves both time and effort, and it makes debugging much easier.
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.