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.
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.
I am preparing for an OCJP. I came across this statement in Kathy Sierra's book.
Interfaces are not part of Object hierarchy in Java
I am just curious and want to know why ?
In order to precise things a bit:
An interface is not part of the object hierarchy, meaning that an interface which does not extend another one has no supertype.
However, an instance typed as an interface is always an Object, otherwise you would not be able to write things like:
interface MyInterface { //no supertype.
}
MyInterface var = new MyInterface(){};
var.toString(); //toString method is defined on Object class.
as you know an interface can not inherits from any class, so it can not be inherited directly or indirectly from Object class, that's why an interface does not belongs to Object hierarchy like other classes for example String,etc
This is my question
What is the use of a Abstract class even though we cant instantiate a abstract class?
is there a indirect way of creating instances of an Abstract class?
Basically, an abstract class is a class that is not fully implemented. If you know that you will have several subclasses of a class, but that you will never declare objects of the class itself, you should consider making the class abstract. Say, for instance, that you have an array of items, and you want them to all act fairly similarly except in certain circumstances. You could make an abstract superclass, and have all these items be members of subclasses of it. Then have the method whose behaviors differ among the different items be abstract in the superclass - but implement them in the subclass. This way, you can put them all in one array (etc) but they will all respond differently to certain method calls.
Did you understand what is an interface in java ? It is in fact, a programming agreement between the architect, developers. That will not contain any method definitions but their signatures. Since architects need to assure to other world creatures who use this code that this works in all of their scenarios. The same way, if some code is so much standard, and an architect cum developer wishes to use it for a de-facto method, he may include that too in an interface. But this distinction made another introduction to java and that is called as Abstract Class concept.
Abstract classes have importance in relation to runtime polymorphism.
I read that interfaces do not have a constructors, which means it will not call super() of its super class. I also read that each and every class in Java is a subclass of Object
What about an interface, is it subclass of Object? Why?
No it's not. An interface cannot be instantiated to form an object, it is not a class.
An interface is a named collection of method definitions (without implementations). An interface can also include constant declarations.
Interface and class have some basic difference and one of them is do not have a constructors. Actually interface does not made for it and you cannot instantiate interface but there is way you can still instantiate interface.
interface Interface{
abstract String fun();
}
Interface interfc=new Interface() {
#Override
public String fun() {
return super.toString();
}
};
Type type=interfc.getClass();
Here interface has been instantiated as anonymous class.But still you cannot place constructor here according to java language specification. But still you can use super class Which will be immediately super class of this anonymous class.
An anonymous class cannot have an explicitly declared constructor.
And there is alternative solution of this that is using final variable in super class.
No interface is a subclass of Object class, since interface cannot extend a class whether implicit or explicit.
Reason for constructor is to create an instance, since interface cannot be instantiated as they don't provide any functionality they are just a contract only class can be instantiated hence they have constructor.
While some people suggest thinking of interfaces as "can-do" rather than "is-a" relationships, I think it's more helpful to think of them "is a __er" or "is a __able thing". To use a real-world analogy, a book (dead-tree edition), a bound paper magazine, a newspaper, a promotional advertising flyer, a sign, and a scrap of paper with some words written on it, are all "readable things". If someone were to show another person a book and ask "Is this a readable thing", the answer would be that it is. On the other hand, if someone were to show another person a book and ask "What is this?" the response would not be "A readable thing", but more likely "A book", or perhaps "A hardcover fifth-printing copy of the second U.S. edition of the novel 'Great Expectations' by Charles Dickens". Any type of "readable thing" has some identity beyond merely being a "readable thing".
Likewise with Java interfaces. An object may implement an arbitrary number of interfaces, but every object must have a type in addition to the set of interfaces it supports. Note that it is possible to define a method which will return a new object of unknown type that implements an interface; that would be equivalent to asking someone, "Please get me something to read" without specifying what type of object was desired. Such a method could select a type of object to return, and give the caller one which is "readable". Constructors, however, unlike general methods, require the caller to specify precisely what type of object is desired. Merely specifying that an object is "readable" would not be a sufficient specification.
No interface can not have constructor. Because interface support multiple inheritance. That means if a class inherit two interface then due to constructor chaining there will be ambiguity which constructor will be called from class constructor.
Can anyone tell me how the implicit inheritance works in java internally?
What I mean is if I create a class how exactly it extends the Object class in the JVM?
Thanks in advance.
Java forces inheritance on every class. If you do not explicitly inherit from a class, then by default Java assumes that you are inheriting from the class called Object, which does not do much, but does have several useful methods :
it implies that every class is descended from Object, since whatever class you inherit from must have inherited from something, which would be either Object or something that inherited from something, etc.
the concept of polymorphism implies that you could store any type of object in a variable whose type was Object
For all practical reasons, you can think that class X { is a syntax sugar for class X extends Object {—that's it.
Apart from the Object class, every class in Java must have a super-class.
There is nothing special about implicit inheritance. It is simply a syntactic shortcut that means you don't have to write extends Object. At a semantic level, implicit inheritance works exactly the same way as explicit inheritance.
In practice, this means that every class inherits certain standard methods from Object ... unless the methods are overridden. Examples include equals(Object), hashcode() and toString() which are frequently overridden, and getClass() that cannot be overridden.