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.
Related
I was reading an article on Inheritance . Few facts were listed on Inheritance but one point i couldn't understand what is Default superclass and its explanation. What is Default superclass?
Default Superclass : Except Object class, 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 the Object class.
The default superclass is Object (more precisely java.lang.Object). If a class does not define a direct superclass explicitly (via extends), then Object is implicitly a superclass of that class.
Have a look at the following example which graphically shows this:
public class A {}
public class B extends A {}
public class C {}
Note that his rule does not apply to Object itself since this would produce a cyclic inheritance. In other words, java.lang.Object is the root of the class hierarchy.
Except Object class, which has no Super Class, 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 the Object class
Points to understand first:
There is a class Object in java which is already available with the JRE libraries.
When you define a class without an extends keyword, your class will by default extend the Object class in Java.
Even if you extend another class in your new class, the parent or its parent transitively inherits the Object class.
Simple way to understand - after you define a class with / without a parent class, create an object for it. If you are using an IDE, you can see that there are some method suggestions which is not implemented in your class (or parent ). Methods like clone() equals() hashCode() wait() etc. Where did these methods/ behaviors come from to your object ? - Yes it came from the ultimate parent Object
The default inheritance is implicit and handled by the Java itself. Hope this makes your understanding better.
object class is base class for every class you create.
when you create an object of your class then constructor of object class is called.
The Object class in Java is the default superclass. Object class is inherited into a newly created class by default if it does not explicitly inherited from any other class. So every class that you create in Java programming is inherently a child class of the Object.
All classes in Java extend Object class by default, and they are subclass of object class, the only exception of this convention is the Object class itself, object class does not extend any class by default, this is the whole idea.
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.
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 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.
I'm reading a book about data structures in java, and it's talking about iterators now. I saw the following code and it seems odd to me. In the following code, AbstractIterator is an abstract class that implements Iterator<E>, UniqueFilteris a subclass of AbstractIterator that is not abstract, and data is a Vector. I guess I don't understand how in the first line you can take the output of the Vector.iterator() method and cast that into an abstract class. After line 1, is dataIterator not an instantiated instance of an abstract class?
AbstractIterator<String> dataIterator =
(AbstractIterator<String>)data.iterator();
AbstractIterator<String> ui = new UniqueFilter(dataIterator);
The problem is that there are two different types we are talking about. The (run time) type of an object and the (compile time) type of a reference.
dataIterator is a reference of an abstract type - that's ok.
data.iterator() returns a reference to an object whose type is not clear from the example, but apparently it's a concrete type which inherits from AbstractIterator<String> - that's ok
You can always assign a reference to object of type B to a reference to object of type A if B is a child of A, even if A is abstract (or interface). You actually don't need the cast.
So after line one dataIterator is still a reference of type AbstractIterator<String>, but it's a reference to an object of a concrete type which implements AbstractIterator<String>.
Remember, in JAVA all the object variables are actually references.
UniqueFilter is irrelevant for this question, btw.
Inheritance means IS-A. If a Child inherits from a Parent, then Child IS-A Parent and can be used in any situation where a Parent is called for.
Since UniqueFilter IS-A AbstractIterator, this means you can cast it just as your code shows.
Why would you not believe the JVM?
After line 1, is dataIterator not an instantiated instance of an abstract class?
It is an instance of a UniqueFilter which also makes it an AbstractIterator by inheritance. Attempting to "instantiate and instance of an abstract class" means attempting to call the abstract class' constructor, that's what's not allowed, and that's what's not happening here.
Abstract Class is a class that cannot be instantiated. Often it will include one or more methods that are also declared abstract and must be implemented by subclasses for the subclass to be concrete (opposite of abstract), and therefore able to be instantiated.
UniqueFilter is a subclass of AbstractIterator ( an abstract class). Since this is a IS-A kind of relationship, you cannot declare an instance of abstract class.
If you want to create an instance for abstract class, first you create a concrete subclass and create an instance for that and use it.
From what you've described it looks like there's an assumption that can be made that has been overlooked; that the implementing type returned by data.iterator() here is a subclass of AbstractIterator<String>.
If this assumption can be made, then the first statement becomes obvious as an object can be legally type cast to any object up the inheritance hierarchy, in this case an AbstractIterator<String>.
In this case dataIterator is NOT an instantiated instance of an abstract class; its not being instantiated here (i.e new AbstractIterator<String(...)), its just a reference to the instantiated instance returned by Vector.iterator() with the type being that of a superclass of the actual returned type, which happens to be an abstract class.
HeadofState is an abstract (by the English meaning of the word abstract) term.
There is no country in the world where the official title of its head-of-state is Head-of-State.
A head-of-state, even though abstract in language and existence, is a super class or super category of titles like sultan, president, premier, prime minister, beloved father, etc.
So, even though the existence of head-of-state cannot be instantiated in its abstract form, you can instantiate (by democratic means, hereditary or by coup) a president, a prime minister, or any honcho-what-nots.
So say, a prime minister has been instantiated, it can then be equated to its abstract parent terminology of "Head-of-State".
So even though an abstract class cannot be instantiated, an implementation of that abstract class can be instantiated. That is what factories can do. Factories are a means to create instances of abstract classes.
Just like abstract classes, interfaces cannot be instantiated but must be implemented. Abstract classes are partially implemented, whereas interfaces are totally unimplemented by themselves. Abstract classes and interfaces depends on derivative classes to complete their existence. Of course, the obsessive OO-purist's technical terminology would clarify that abstract classes are "extended" and interfaces are "inherited".
For example, HttpServletRequest is an interface. You cannot instanstiate it directly. When your JSP grabs its http servlet request, it works the same whether you are in Jetty or Tomcat. However, if you inspect carefully, the actual class instantiated by the HttpServletRequest factory in Jetty is different from that created in Tomcat. But, since both of them implement HttpServletRequest, those instances can simply be equated to a variable whose type is HttpServletRequest.
You should read up on abstract classes vs interfaces and how interfaces are concocted to allow pseudo-multiple inheritance in Java. Once you understand the role of interfaces, you would then understand abstract classes. In the realm of object-oriented flame wars, some people think that Interfaces was a brilliant break-thro in multiple inheritance. Some people think interfaces have nothing to do with multiple inheritances. In my own less than humble opinion, interfaces are a poor and failed attempt at socialist's paternalistic indulgence to prevent me from getting into trouble that presumes that I don't know how to take care of myself.